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";

export async function getCourseBySlug(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .get('/courses/:slug', {
      schema: {
        summary: 'Get course by slug',
        tags: ['courses'],
        params: z.object({
          slug: z.string(),
        }),
        response: {
          200: z.object({
            course: z.object({
              id: z.string(),
              title: z.string(),
              description: z.string(),
              image: z.string(),
              certificate: z.boolean(),
              status: z.boolean(),
            }).nullable(),
          }),
        },
      },
    }, async (request, reply) => {
      const { slug } = request.params;

      const course = await prisma.course.findUnique({
        where: {
          slug: slug,
          status: true,
        },
        select: {
          id: true,
          title: true,
          description: true,
          image: true,
          certificate: true,
          status: true,
        }
      });

      if (!course) {
        return reply.status(404).send({ course: null });
      }

      const formattedCourse = {
        id: course.id,
        title: course.title,
        description: course.description,
        image: course.image,
        certificate: course.certificate,
        status: course.status,
      };

      return reply.send({
        course: formattedCourse,
      });
    })
}
