import { FastifyInstance } from "fastify";
import { ZodTypeProvider } from "fastify-type-provider-zod";
import { z } from "zod";
import { prisma } from "../../lib/prisma";
import { auth } from "../../middlewares/auth"
import { UnauthorizedError } from "../_errors/unauthorized-error";

export async function getUsers(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .register(auth)
    .get('/users', {
      schema: {
        summary: 'Get users',
        security: [{ bearerAuth: [] }],
        tags: ['users'],
        querystring: z.object({
          query: z.string().nullish(),
          pageIndex: z.string().nullish().default('0').transform(Number),
        }),
        response: {
          200: z.object({
            users: z.array(
              z.object({
                id: z.string(),
                name: z.string(),
                email: z.string(),
                phone: z.string(),
                cpf: z.string(),
                zip: z.string(),
                address: z.string(),
                number: z.string().nullable(),
                complement: z.string().nullable(),
                district: z.string().nullable(),
                city: z.string(),
                state: z.string(),
                details: z.string().nullable(),
                role: z.enum(["manager", "customer"]),
                createdAt: z.date(),
              })
            ),
            total: z.number(),
          }),
        },
      },

    }, async (request, reply) => {
      const { pageIndex, query } = request.query
      const userId = await request.getCurrentUserId()

      if (!userId) {
        throw new UnauthorizedError('You do not have permission to access this route')
      }

      // Verifica se o usuário é Admin (manager)
      const userVerify = await prisma.user.findUnique({
        where: {
          id: userId
        }
      })

      if (userVerify?.role !== 'manager') {
        throw new UnauthorizedError('You do not have permission to access this route')
      }

      const [users, total] = await Promise.all([
        prisma.user.findMany({
          select: {
            id: true,
            name: true,
            email: true,
            phone: true,
            cpf: true,
            zip: true,
            address: true,
            number: true,
            complement: true,
            district: true,
            city: true,
            state: true,
            details: true,
            role: true,
            createdAt: true,
          },
          where: {
            role: 'customer',
            ...(query ? {
              OR: [
                { name: { contains: query, mode: 'insensitive' } },
                { email: { contains: query, mode: 'insensitive' } },
              ],
            } : {}),
          },
          take: 10,
          skip: pageIndex * 10,
          orderBy: {
            name: 'asc'
          }
        }),
        prisma.user.count({
          where: {
            role: 'customer',
            ...(query ? {
              OR: [
                { name: { contains: query, mode: 'insensitive' } },
                { email: { contains: query, mode: 'insensitive' } },
              ],
            } : {}),
          },
        })
      ])

      return reply.send({
        users: users.map(user => {
          return {
            id: user.id,
            name: user.name,
            email: user.email,
            phone: user.phone,
            cpf: user.cpf,
            zip: user.zip,
            address: user.address,
            number: user.number,
            complement: user.complement,
            district: user.district,
            city: user.city,
            state: user.state,
            details: user.details,
            role: user.role,
            createdAt: user.createdAt,
          }
        }),
        total,
      })
    })

}