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";

export async function getAvailableCourses(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/students/:studentId/available-courses', {
      schema: {
        summary: 'Get available courses for a student',
        tags: ['courses'],
        params: z.object({
          studentId: z.string().cuid(),
        }),
        response: {
          200: z.object({
            courses: z.array(
              z.object({
                id: z.string(),
                title: z.string(),
                description: z.string(),
                image: z.string(),
                certificate: z.boolean(),
                status: z.boolean(),
              })
            )
          })
        },
      },
    }, async (request, reply) => {
      const { studentId } = request.params;

      // Check if the student exists
      const student = await prisma.user.findUnique({ where: { id: studentId } });
      if (!student) {
        throw new BadRequest('Student not found.');
      }

      // Get the courses the student is already enrolled in
      const enrolledCourses = await prisma.userCourse.findMany({
        where: {
          userId: studentId,
        },
        select: {
          courseId: true,
        },
      });

      const enrolledCourseIds = enrolledCourses.map(ec => ec.courseId);

      // Get the courses the student is not enrolled in
      const availableCourses = await prisma.course.findMany({
        where: {
          id: {
            notIn: enrolledCourseIds,
          },
          status: true,
        },
      });

      return reply.status(200).send({ courses: availableCourses });
    });
}
