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 getCourseIdBySlug(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .register(auth)
    .get('/get-course-id/:slug', {
      schema: {
        summary: 'Get course ID by slug',
        security: [{ bearerAuth: [] }],
        tags: ['courses'],
        params: z.object({
          slug: z.string(),
        }),
        response: {
          200: z.object({
            id: 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 course = await prisma.course.findUnique({
        where: { slug },
        select: { id: true },
      });

      if (!course) {
        return reply.status(404).send({ message: 'Course not found' });
      }

      return reply.send({ id: course.id });
    });
}
