import { FastifyInstance } from "fastify";
import { ZodTypeProvider } from "fastify-type-provider-zod";
import { z } from "zod";
import { prisma } from "../../../lib/prisma";

export async function getTotalDurationVideos(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/active-courses-duration', {
      schema: {
        summary: 'Get total duration of active courses',
        tags: ['courses'],
        response: {
          200: z.object({
            totalDuration: z.number(),
          }),
        },
      },
    }, async (request, reply) => {
      const activeCourses = await prisma.course.findMany({
        where: {
          status: true,
        },
        select: {
          Module: {
            select: {
              Class: {
                select: {
                  duration: true,
                },
              },
            },
          },
        },
      });

      // Calculate the total duration of all classes in active courses
      const totalDuration = activeCourses.reduce((total, course) => {
        return total + course.Module.reduce((moduleTotal, module) => {
          return moduleTotal + module.Class.reduce((classTotal, cls) => {
            return classTotal + cls.duration;
          }, 0);
        }, 0);
      }, 0);

      return reply.send({
        totalDuration,
      });
    });
}
