import { FastifyInstance } from "fastify";
import { ZodTypeProvider } from "fastify-type-provider-zod";
import { z } from "zod";
import { prisma } from "../../lib/prisma";
import { BadRequest } from "../_errors/bad-request";

export async function getUser(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/users/:userId', {
      schema: {
        summary: 'Get a user',
        tags: ['users'],
        params: z.object({
          userId: z.string().cuid(),
        }),
        response: {
          200: z.object({
            user: 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(),
            }),
          }),
        },
      },
    }, async (request, reply) => {
      const { userId } = request.params;

      const user = await prisma.user.findUnique({
        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: {
          id: userId,
        },
      });

      if (!user) {
        throw new BadRequest('User not found.');
      }

      return reply.send({
        user: {
          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,
        },
      });
    });
}
