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";

// Utility function to format the month data
function formatMonthData(monthData: { createdAt: Date; _count: { id: number } }[]) {
  const months = [
    { name: "Jan", total: 0 },
    { name: "Fev", total: 0 },
    { name: "Mar", total: 0 },
    { name: "Abr", total: 0 },
    { name: "Mai", total: 0 },
    { name: "Jun", total: 0 },
    { name: "Jul", total: 0 },
    { name: "Ago", total: 0 },
    { name: "Set", total: 0 },
    { name: "Out", total: 0 },
    { name: "Nov", total: 0 },
    { name: "Dez", total: 0 },
  ];

  monthData.forEach(data => {
    const monthIndex = new Date(data.createdAt).getMonth();
    months[monthIndex].total = data._count.id;
  });

  return months;
}

// Type guard to check if error is an instance of Error
function isError(error: unknown): error is Error {
  return error instanceof Error;
}

export async function getUserCourseCountByMonth(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/user-course-count-by-month', {
      schema: {
        summary: 'Get user course count by month',
        tags: ['user-courses'],
        response: {
          200: z.array(z.object({
            name: z.string(),
            total: z.number(),
          })),
        },
      },
    }, async (request, reply) => {
      try {
        const groupedData = await prisma.userCourse.groupBy({
          by: ['createdAt'],
          _count: {
            id: true,
          },
        });

        const formattedData = formatMonthData(groupedData);

        return reply.send(formattedData);
      } catch (error) {
        if (isError(error)) {
          throw new BadRequest(error.message);
        } else {
          throw new BadRequest('An unknown error occurred');
        }
      }
    });
}
