import { FastifyReply, FastifyRequest } from "fastify";
import prisma from "../../utils/prisma";
import { IdParamsSchema } from "../../utils/schema";
import { VideoSchema } from "./schema";

// ------------------------------------------------------------------------------------

export async function getVideos(req: FastifyRequest, reply: FastifyReply) {
  const videos = await prisma.video.findMany({
    orderBy: {
      date: "desc",
    },
  });

  return reply.code(200).send(videos);
}

// ------------------------------------------------------------------------------------

export async function getVideo(
  req: FastifyRequest<{
    Params: IdParamsSchema;
  }>,
  reply: FastifyReply
) {
  const id = req.params.id;

  const video = await prisma.video.findUnique({
    where: {
      id: id,
    },
  });

  if (!video) {
    return reply.code(404).send({
      message: "Cette vidéo n'existe pas",
    });
  }

  return reply.code(200).send(video);
}

// ------------------------------------------------------------------------------------

export async function createVideo(
  req: FastifyRequest<{
    Body: VideoSchema;
  }>,
  reply: FastifyReply
) {
  const data = req.body;

  const video = await prisma.video.create({
    data: {
      title: data.title,
      date: data.date,
      link: data.link,
    },
  });
  return reply.code(200).send(video);
}

// ------------------------------------------------------------------------------------

export async function editVideo(
  req: FastifyRequest<{
    Params: IdParamsSchema;
    Body: VideoSchema;
  }>,
  reply: FastifyReply
) {
  const id = req.params.id;
  const data = req.body;

  const video = await prisma.video.findUnique({
    where: {
      id: id,
    },
  });

  if (!video) {
    return reply.code(404).send({
      message: "Cette vidéo n'existe pas",
    });
  }

  const newVideo = await prisma.video.update({
    where: { id: id },
    data: {
      title: data.title,
      date: data.date,
      link: data.link,
    },
  });
  return reply.code(200).send(newVideo);
}

// ------------------------------------------------------------------------------------

export async function deleteVideo(
  req: FastifyRequest<{
    Params: IdParamsSchema;
  }>,
  reply: FastifyReply
) {
  const id = req.params.id;

  const video = await prisma.video.findUnique({
    where: {
      id: id,
    },
  });

  if (!video) {
    return reply.code(404).send({
      message: "Cette vidéo n'existe pas",
    });
  }

  await prisma.video.delete({
    where: { id: id },
  });

  return reply.code(200).send({});
}

// ------------------------------------------------------------------------------------
