import { FastifyInstance } from "fastify";
import { ZodTypeProvider } from "fastify-type-provider-zod";
import { z } from "zod";
import { generateSlug } from "../../utils/generate-slug"
import { prisma } from "../../lib/prisma";
import { BadRequest } from "../_errors/bad-request";

export async function createCourse(app: FastifyInstance) {
  app
  .withTypeProvider<ZodTypeProvider>()
  .post('/courses', {
    schema: {
      summary: 'Create a course',
      tags: ['courses'],
      body: z.object({
        title: z.string().min(4),
        description: z.string(),
        image: z.string(),
        certificate: z.boolean(),
      }),
      response: {
        201: z.object({
          courseId: z.string().cuid(),
        })
      },
    },
  }, async (request, reply) => {

    const {
      title,
      description,
      image,
      certificate,
      } = request.body;


    // Check if a course with the same title already exists
    const slug = generateSlug(title)

    const courseWithSameSlug = await prisma.course.findUnique({
      where: {
        slug,
      }
    })

    if (courseWithSameSlug !== null) {
      throw new BadRequest('Another course with the same title already exists.');
    }

    // Create the course in the database
    const course = await prisma.course.create({
      data: {
        title,
        description,
        slug,
        image,
        certificate,
        status: true
      },
    });

    return reply.status(201).send({ courseId: course.id });
  });
}
