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 getCourseModules(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .register(auth)
    .get('/course-modules/:courseId', {
      schema: {
        summary: 'Get course modules and classes with details',
        security: [{ bearerAuth: [] }],
        tags: ['courses'],
        params: z.object({
          courseId: z.string(),
        }),
        response: {
          200: z.object({
            modules: z.array(
              z.object({
                id: z.string(),
                title: z.string(),
                totalDuration: z.number(),
                numberOfClasses: z.number(),
                active: z.boolean(), // Indica se o módulo está ativo ou não
                classes: z.array(
                  z.object({
                    id: z.string(),
                    title: z.string(),
                    slug: z.string(),
                    duration: z.number(),
                    watched: z.boolean(),
                  })
                )
              })
            ),
          }),
        },
      },
    }, async (request, reply) => {
      const { courseId } = request.params;
      const userId = await request.getCurrentUserId();

      if (!userId) {
        throw new UnauthorizedError('You do not have permission to access this route');
      }

      const modules = await prisma.module.findMany({
        where: { courseId },
        orderBy: { id: 'asc' }, // Ordena os módulos pelo ID
        select: {
          id: true,
          title: true,
          Class: {
            select: {
              id: true,
              title: true,
              slug: true,
              duration: true,
              ClassAttended: {
                where: {
                  userId,
                },
                select: {
                  id: true,
                },
              },
            },
          },
        },
      });

      let previousModuleCompleted = true;
      const formattedModules = [];

      for (let i = 0; i < modules.length; i++) {
        const module = modules[i];
        const totalDuration = module.Class.reduce((sum, cls) => sum + cls.duration, 0);
        const numberOfClasses = module.Class.length;

        const classes = module.Class.map(cls => ({
          id: cls.id,
          title: cls.title,
          slug: cls.slug,
          duration: cls.duration,
          watched: cls.ClassAttended.length > 0,
        }));

        // O primeiro módulo é sempre ativo
        const active = i === 0 ? true : previousModuleCompleted;
        previousModuleCompleted = classes.every(cls => cls.watched);

        formattedModules.push({
          id: module.id,
          title: module.title,
          totalDuration,
          numberOfClasses,
          active,
          classes,
        });
      }

      return reply.send({
        modules: formattedModules,
      });
    });
}
