import { FastifyInstance } from "fastify";
import { ZodTypeProvider } from "fastify-type-provider-zod";
import { z } from "zod";
import { prisma } from "../../lib/prisma";

export async function getCourseAndModule(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/course-module/:courseId/:moduleId', {
      schema: {
        summary: 'Get course and module information',
        tags: ['courses', 'modules'],
        params: z.object({
          courseId: z.string(),
          moduleId: z.string(),
        }),
        response: {
          200: z.object({
            course: z.object({
              id: z.string(),
              name: z.string(),
            }),
            module: z.object({
              id: z.string(),
              name: z.string(),
            }),
          }),
          404: z.object({
            message: z.string(),
          }),
        },
      },
    }, async (request, reply) => {
      const { courseId, moduleId } = request.params;

      // Fetch the course data
      const course = await prisma.course.findUnique({
        where: {
          id: courseId,
        },
        select: {
          id: true,
          title: true,
        },
      });

      // Fetch the module data
      const module = await prisma.module.findUnique({
        where: {
          id: moduleId,
        },
        select: {
          id: true,
          title: true,
        },
      });

      // Check if course or module was not found
      if (!course) {
        return reply.code(404).send({ message: 'Course not found' });
      }

      if (!module) {
        return reply.code(404).send({ message: 'Module not found' });
      }

      return reply.send({
        course: {
          id: course.id,
          name: course.title,
        },
        module: {
          id: module.id,
          name: module.title,
        },
      });
    });
}
