import { FastifyReply, FastifyRequest } from "fastify";
import prisma from "../../utils/prisma";
import { getPresignedUrl, minioClient } from "../../utils/minio";
import { bucketName } from "../../utils/consts";

export async function getEditions(req: FastifyRequest, reply: FastifyReply) {
  const editions = await prisma.edition.findMany({
    orderBy: {
      title: "asc",
    },
    include: {
      category: true,
    },
  });

  const newEditions = await Promise.all(
    editions.map(async (edition) => ({
      id: edition.id,
      title: edition.title,
      categoryId: edition.categoryId,
      category: edition.category,
      presignedDocument: await getPresignedUrl(edition.document),
      presignedImage: edition.image
        ? await getPresignedUrl(edition.image)
        : null,
    }))
  );

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

export async function getPdf(req: FastifyRequest, reply: FastifyReply) {
  const stream = await minioClient.getObject(
    bucketName,
    "editions/2ffbbf1137788b2684360cda02112b27_doc.pdf"
  );
  reply.header("Content-Type", "application/pdf");
  reply.header("Content-Disposition", 'inline; filename="your-pdf.pdf"');
  return reply.send(stream);
}
