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 markClassAsWatched(app: FastifyInstance) {
  app
    .withTypeProvider<ZodTypeProvider>()
    .register(auth)
    .post('/mark-class-watched', {
      schema: {
        summary: 'Mark class as watched',
        security: [{ bearerAuth: [] }],
        tags: ['classes'],
        body: z.object({
          classId: z.string(),
        }),
        response: {
          200: z.object({
            message: z.string(),
          }),
          400: z.object({
            message: z.string(),
          }),
        },
      },
    }, async (request, reply) => {
      const { classId } = request.body;
      const userId = await request.getCurrentUserId();

      if (!userId) {
        throw new UnauthorizedError('You do not have permission to access this route');
      }

      // Verificar se a aula já foi marcada como assistida
      const classAttended = await prisma.classAttended.findFirst({
        where: {
          userId,
          classId,
        },
      });

      if (classAttended) {
        return reply.status(200).send({ message: 'Class already marked as watched' });
      }

      // Marcar a aula como assistida
      await prisma.classAttended.create({
        data: {
          userId,
          classId,
        },
      });

      return reply.send({ message: 'Class marked as watched' });
    });
}
