import { FastifyInstance } from "fastify";
import { ZodTypeProvider } from "fastify-type-provider-zod";
import { z } from "zod";
import { prisma } from "../../../lib/prisma";

export async function getLastFiveCustomers(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/last-five-customers', {
      schema: {
        summary: 'Get last five customers',
        tags: ['users'],
        response: {
          200: z.array(z.object({
            id: z.string(),
            name: z.string(),
            email: z.string(),
            createdAt: z.string(),
            abbreviation: z.string(),
          })),
        },
      },
    }, async (request, reply) => {
      const users = await prisma.user.findMany({
        where: {
          role: 'customer',
        },
        select: {
          id: true,
          name: true,
          email: true,
          createdAt: true,
        },
        orderBy: {
          createdAt: 'desc',
        },
        take: 5,
      });

      const formattedUsers = users.map(user => {
        const nameParts = user.name.split(' ');
        const firstInitial = nameParts[0]?.charAt(0).toUpperCase() || '';
        const lastInitial = nameParts[nameParts.length - 1]?.charAt(0).toUpperCase() || '';
        const abbreviation = `${firstInitial}${lastInitial}`;

        return {
          id: user.id,
          name: user.name,
          email: user.email,
          createdAt: user.createdAt.toISOString(),
          abbreviation,
        };
      });

      return reply.send(formattedUsers);
    });
}
