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

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

export async function getTrainings(req: FastifyRequest, reply: FastifyReply) {
  const trainings = await prisma.training.findMany({
    orderBy: {
      date: "desc",
    },
    select: {
      id: true,
      title: true,
      type: true,
      date: true,
      place: true,
    },
  });

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

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

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

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

  if (!training) {
    return reply.code(404).send({
      message: "Cette formation n'existe pas",
    });
  }

  const finalTraining = {
    ...training,
    presignedDocument: training.document
      ? await getPresignedUrl(training.document)
      : null,
  };

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

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