import { prisma } from '../../../lib/prisma.js'

export async function registerAdminTestChecklistRoutes(fastify) {
  fastify.get('/api/admin/test-checklist', { preHandler: [fastify.verifyAdmin] }, async (request, reply) => {
    const results = await prisma.checklistResult.findMany()
    const resultMap = {}
    for (const r of results) {
      resultMap[r.itemKey] = { passed: r.passed, comment: r.comment, checkedAt: r.checkedAt.toISOString() }
    }
    return { results: resultMap }
  })

  fastify.patch('/api/admin/test-checklist', { preHandler: [fastify.verifyAdmin] }, async (request, reply) => {
    const { itemKey, passed, comment } = request.body || {}
    if (!itemKey || typeof passed !== 'boolean') {
      return reply.code(400).send({ error: 'itemKey и passed (boolean) обязательны' })
    }
    if (comment !== undefined && comment !== null && typeof comment !== 'string') {
      return reply.code(400).send({ error: 'comment должен быть строкой' })
    }
    if (comment !== undefined && comment !== null && comment.length > 2000) {
      return reply.code(400).send({ error: 'Комментарий слишком длинный (макс. 2000 символов)' })
    }

    const result = await prisma.checklistResult.upsert({
      where: { itemKey },
      create: { itemKey, passed, comment: passed ? null : comment || null },
      update: { passed, comment: passed ? null : (comment ?? undefined), checkedAt: new Date() },
    })

    return {
      result: {
        itemKey: result.itemKey,
        passed: result.passed,
        comment: result.comment,
        checkedAt: result.checkedAt.toISOString(),
      },
    }
  })

  fastify.post('/api/admin/test-checklist/reset', { preHandler: [fastify.verifyAdmin] }, async (request, reply) => {
    await prisma.checklistResult.deleteMany({})
    return { ok: true }
  })
}
