import { FastifyInstance } from "fastify";
import { ZodTypeProvider } from "fastify-type-provider-zod";
import { z } from "zod";
import { prisma } from "../../lib/prisma";
import { auth } from "../../middlewares/auth";
import { UnauthorizedError } from "../_errors/unauthorized-error";

export async function getCourseIdByClassSlug(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .register(auth)
    .get('/class-course-id/:slug', {
      schema: {
        summary: 'Get course ID by class slug',
        security: [{ bearerAuth: [] }],
        tags: ['classes'],
        params: z.object({
          slug: z.string(),
        }),
        response: {
          200: z.object({
            courseId: z.string(),
          }),
          404: z.object({
            message: z.string(),
          }),
        },
      },
    }, async (request, reply) => {
      const { slug } = request.params;
      const userId = await request.getCurrentUserId();

      if (!userId) {
        throw new UnauthorizedError('You do not have permission to access this route');
      }

      const classData = await prisma.class.findUnique({
        where: { slug: slug },
        select: {
          module: {
            select: {
              courseId: true,
            }
          }
        },
      });

      if (!classData) {
        return reply.status(404).send({ message: 'Class not found' });
      }

      return reply.send({
        courseId: classData.module.courseId,
      });
    });
}