const { Timestamp } = require("firebase-admin/firestore");
const admin = require("firebase-admin");
const React = require("react");

const { refsList, genkitInstance } = require("../..");

exports.getCompanyDataFromUserID = async ({ userID = null }) => {
  try {
    if (!userID) {
      throw new Error("No userID provided");
    }

    const companySnapshot =
      (await refsList.companies.where("mainOwnerID", "==", userID).get())
        .docs?.[0] || null;

    if (!companySnapshot) {
      throw new Error("Company not found");
    }

    const companyData =
      { ...companySnapshot.data(), companyID: companySnapshot.id } || null;

    return companyData;
  } catch (error) {
    console.log(error);
    throw error;
  }
};

const logNewAction = async ({
  description = "",
  userID = null,
  isSuccess = true,
}) => {
  try {
    if (!description?.length) {
      throw new Error("Missing required fields");
    }

    await refsList.logs.add({
      isSuccess,
      description,
      userID,
      timestamp: Timestamp.now(),
    });
  } catch (error) {
    console.log(error);
    throw error;
  }
};

exports.logNewAction = logNewAction;

// Fonction pour générer et uploader le PDF
exports.generateDocument = async ({ template, data, filePath }) => {
  try {
    // Générer le PDF en buffer
    // Import dynamique de Quote en ESM
    const { pdf } = await import("@react-pdf/renderer");

    // Générer le PDF en buffer
    const buffer = await pdf(
      React.createElement(template, {
        ...data,
      })
    ).toBuffer();

    // Uploader le PDF dans Firebase Storage
    const bucket = admin.storage().bucket("gs://starsclick.appspot.com/");
    const file = bucket.file(filePath);

    console.log(`Uploading PDF to Firebase Storage as ${filePath}...`);

    const chunks = [];
    buffer.on("data", (chunk) => chunks.push(chunk));
    buffer.on("end", async () => {
      const pdfBuffer = Buffer.concat(chunks);

      await file.save(pdfBuffer, {
        metadata: {
          contentType: "application/pdf",
        },
      });
    });

    // Générer une URL signée
    const expiresAt = Date.now() + 1000 * 60 * 60 * 24 * 7; // Expire dans 7 jours
    const [url] = await file.getSignedUrl({
      action: "read",
      expires: expiresAt,
    });

    console.log(`PDF uploaded to Firebase Storage as ${filePath}.`);
    console.log(`PDF URL: ${url}`);

    return { downloadURL: url };
  } catch (error) {
    console.error("Error generating or uploading PDF:", error);
    throw error;
  }
};

exports.generateAI = async ({ prompt = "", schema, config = {} }) => {
  if (prompt?.length < 1) {
    throw new Error(
      "Vous devez spécifier un prompt pour effectuer cette action."
    );
  }

  let attempts = 0;
  let result;

  while (attempts < 3) {
    try {
      const { output } = await genkitInstance.generate({
        system:
          "Voici un prompt, le contenu généré doit toujours être en français: ",
        prompt,
        config: {
          ...config,
        },
        output: { schema },
      });

      console.log("Résultat de la génération par IA:", output);

      result = output;

      await logNewAction({
        description: `Génération par IA réussie`,
        isSuccess: true,
      });

      return result;
    } catch (error) {
      attempts += 1;
      console.log(`Tentative ${attempts} échouée:`, error);

      if (attempts >= 3) {
        await logNewAction({
          description: `Génération par IA échouée après plusieurs tentatives`,
          isSuccess: false,
          error,
        });

        throw new Error(
          "Erreur lors de la génération par IA après plusieurs tentatives, veuillez réessayer."
        );
      }
    }
  }
};

