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 getStudentCourses(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/students/:studentId/courses', {
      schema: {
        summary: 'Get 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(),
                createdAt: z.string(),
                expire: z.string().nullable(),
              })
            )
          })
        },
      },
    }, 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 for the student
      const studentCourses = await prisma.userCourse.findMany({
        where: {
          userId: studentId,
        },
        include: {
          course: true,
        }
      });

      const courses = studentCourses.map(sc => ({
        id: sc.course.id,
        title: sc.course.title,
        description: sc.course.description,
        image: sc.course.image,
        certificate: sc.course.certificate,
        status: sc.course.status,
        createdAt: sc.createdAt.toISOString(),
        expire: sc.expire,
      }));

      return reply.status(200).send({ courses });
    });
}
