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

export async function registerAdminReviewRoutes(fastify) {
  fastify.get(
    '/api/admin/reviews',
    { preHandler: [fastify.verifyAdmin] },
    async (request, reply) => {
      const status = typeof request.query?.status === 'string' ? request.query.status.trim() : 'pending'

      const pageRaw = request.query?.page
      const pageParsed = typeof pageRaw === 'string' ? Number(pageRaw) : Number(pageRaw)
      const page = Number.isFinite(pageParsed) && pageParsed > 0 ? Math.floor(pageParsed) : 1

      const pageSizeRaw = request.query?.pageSize
      const pageSizeParsed = typeof pageSizeRaw === 'string' ? Number(pageSizeRaw) : Number(pageSizeRaw)
      const pageSize = Number.isFinite(pageSizeParsed) && pageSizeParsed > 0 ? Math.floor(pageSizeParsed) : 20
      if (pageSize > 100) return reply.code(400).send({ error: 'pageSize должен быть ≤ 100' })

      const where = status ? { status } : {}
      const total = await prisma.review.count({ where })
      const items = await prisma.review.findMany({
        where,
        include: {
          user: { select: { id: true, email: true, name: true } },
          product: { select: { id: true, title: true } },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      })

      return { items, total, page, pageSize }
    },
  )

  fastify.patch(
    '/api/admin/reviews/:id',
    { preHandler: [fastify.verifyAdmin] },
    async (request, reply) => {
      const { id } = request.params
      const action = String(request.body?.action || '').trim()
      if (action !== 'approve' && action !== 'reject') {
        return reply.code(400).send({ error: 'action должен быть approve или reject' })
      }

      const existing = await prisma.review.findUnique({ where: { id } })
      if (!existing) return reply.code(404).send({ error: 'Отзыв не найден' })

      const updated = await prisma.review.update({
        where: { id },
        data: {
          status: action === 'approve' ? 'approved' : 'rejected',
          moderatedAt: new Date(),
        },
      })
      return { item: updated }
    },
  )
}

