import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import PaginationService from 'App/Services/PaginationService'
import { schema } from '@ioc:Adonis/Core/Validator'
import OcrDevice from 'App/Models/OcrDevice'
import OcrChannel from 'App/Models/OcrChannel'

export default class OcrDevicesController {
    private paginationService = new PaginationService(OcrDevice)

    public async index({ request, auth }: HttpContextContract) {
        const user = auth.user
        const isApiUser = user?.$attributes?.role === 'api'

        const requestData = request.all()
        if (isApiUser) {
            requestData.channel = user.username
        }
        return await this.paginationService.paginate(request.all())
    }

    public async store({ request, bouncer }: HttpContextContract) {
        // await bouncer.authorize('admin')
        const data = await request.validate({
            schema: schema.create({
                id: schema.string(),
                platform: schema.string(),
                channel: schema.string(),
                deviceInfo: schema.string.optional(),
                total: schema.number(),
                scanned: schema.number(),
                ipAddress: schema.string.optional()
            })
        })
        const clientIp = request.ip()
        if (!data.ipAddress) {
            data.ipAddress = clientIp
        }
        const device = await OcrDevice.findBy('id', data.id)
        if (device) {
            device.merge(data)
            return await device.save()
        } else {
            return await OcrDevice.create(data)
        }
    }

    public async show({ params, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        return await OcrDevice.findOrFail(params.id)
    }

    public async plusTotal({ request, response }: HttpContextContract) {
        try {
            const device = await OcrDevice.findBy('id', request.param('id'))
            if (!device) {
                return response.notFound({ message: `未找到ID为 ${request.param('id')} 的OCR设备` })
            }
            device.total += 1
            await device.save()
            return response.ok(device)
        } catch (error) {
            return response.internalServerError({
                message: '更新设备记录数量时发生错误',
                error: error.message
            })
        }
    }

    public async plusScanned({ request, response }: HttpContextContract) {
        const scanCount = Number(request.param('scanCount'))
        if (isNaN(scanCount)) {
            return response.badRequest({ message: 'scanCount 参数必须是有效数字' })
        }

        try {
            const device = await OcrDevice.findBy('id', request.param('id'))
            if (!device) {
                return response.notFound({
                    message: `未找到 ID 为 ${request.param('id')} 的 OCR 设备`
                })
            }

            device.scanned += scanCount
            await device.save()

            return response.ok(device)
        } catch (error) {
            return response.internalServerError({
                message: '更新设备扫描数量时发生错误',
                error: error.message
            })
        }
    }
}
