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 enrollInCourse(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .post('/enroll', {
      schema: {
        summary: 'Enroll a student in a course',
        tags: ['courses'],
        body: z.object({
          userId: z.string().cuid(),
          courseId: z.string().cuid(),
        }),
        response: {
          201: z.object({
            enrollmentId: z.string().cuid(),
          }),
        },
      },
    }, async (request, reply) => {
      const { userId, courseId } = request.body;

      // Check if the user exists
      const user = await prisma.user.findUnique({ where: { id: userId } });
      if (!user) {
        throw new BadRequest('User not found.');
      }

      // Check if the course exists
      const course = await prisma.course.findUnique({ where: { id: courseId } });
      if (!course) {
        throw new BadRequest('Course not found.');
      }

      // Check if the user is already enrolled in the course
      const existingEnrollment = await prisma.userCourse.findFirst({
        where: {
          userId: userId,
          courseId: courseId,
        },
      });

      if (existingEnrollment) {
        throw new BadRequest('User is already enrolled in this course.');
      }

      // Enroll the user in the course
      const enrollment = await prisma.userCourse.create({
        data: {
          userId,
          courseId,
        },
      });

      return reply.status(201).send({ enrollmentId: enrollment.id });
    });
}
