const functions = require("firebase-functions");

const { refsList } = require("..");
const { onCall } = require("firebase-functions/v2/https");

const isStripeProd = false;

const stripe = require("stripe")(isStripeProd ? "sk_live_..." : "sk_test_...");

const baseURL = isStripeProd ? "https://.../" : "https://.../";

exports.createCheckoutSession = onCall(async ({ auth = {}, data = {} }) => {
  try {
    const { userID, productList = [] } = data || {};

    console.log("productList", productList);

    if (!userID) {
      throw new Error("userID is required");
    }

    const currentUserRef = refsList.users.doc(userID);
    const userData = (await currentUserRef.get())?.data() || null;

    let stripeCustomerID;
    const { firstName } = userData || {};

    let updatedCustomerData = {
      name: firstName,
      email: auth.token.email,
    };

    if (userData?.stripeCustomerID) {
      stripeCustomerID = userData.stripeCustomerID;
    } else {
      const customer = await stripe.customers.create({
        ...updatedCustomerData,
      });
      stripeCustomerID = customer.id;
      await currentUserRef.update({ stripeCustomerID });
    }

    await stripe.customers.update(stripeCustomerID, updatedCustomerData);

    let line_items = productList.map((product) => ({
      price: product.priceID,
      quantity: product.quantity,
    }));

    const hasSubscription = productList.some((product) => product.isRenewable);

    let checkoutObject = {
      line_items: line_items,
      mode: hasSubscription ? "subscription" : "payment", // Use "subscription" to support both one-time and subscription items
      ui_mode: "embedded",
      return_url: `${baseURL}explore`,
      customer: stripeCustomerID,
      invoice_creation: {
        enabled: true,
      },
    };

    const session = await stripe.checkout.sessions.create(checkoutObject);

    return session;
  } catch (e) {
    console.log(e);
    throw new functions.https.HttpsError("permission-denied", e.message);
  }
});

exports.getPremiumStatus = onCall(async ({ auth = {}, data = {} }) => {
  // Vérifiez l'authentification de l'utilisateur
  if (!auth) {
    throw new functions.https.HttpsError(
      "unauthenticated",
      "The function must be called while authenticated."
    );
  }

  const uid = auth.uid;

  try {
    // Récupérer l'ID client Stripe depuis Firestore (supposons que vous l'avez stocké précédemment)
    const userDoc = await refsList.users.doc(uid).get();
    const stripeCustomerID = userDoc.data()?.stripeCustomerID || null;

    if (!stripeCustomerID) {
      throw new functions.https.HttpsError(
        "not-found",
        "Stripe customer ID not found."
      );
    }

    // Récupérer les abonnements de l'utilisateur
    const subscriptions = await stripe.subscriptions.list({
      customer: stripeCustomerID,
      status: "all",
    });

    // Récupérer les achats de produits (Invoices)
    const invoices = await stripe.invoices.list({
      customer: stripeCustomerID,
    });

    console.log("subscriptions", subscriptions);
    console.log("invoices", invoices);

    return {
      subscriptions: subscriptions.data,
      invoices: invoices.data,
    };
  } catch (error) {
    console.error("Error fetching Stripe details:", error);
    return {
      subscriptions: [],
      invoices: [],
    };
  }
});

exports.createStripeCustomerPortalSession = onCall(
  async ({ auth = {}, data = {} }) => {
    // Vérifiez l'authentification de l'utilisateur
    if (!auth) {
      throw new functions.https.HttpsError(
        "unauthenticated",
        "The function must be called while authenticated."
      );
    }

    const uid = auth.uid;

    try {
      // Récupérer l'ID client Stripe depuis Firestore (supposons que vous l'avez stocké précédemment)
      const userDoc = await refsList.users.doc(uid).get();
      const stripeCustomerID = userDoc.data().stripeCustomerID;

      if (!stripeCustomerID) {
        throw new functions.https.HttpsError(
          "not-found",
          "Stripe customer ID not found."
        );
      }

      // Créer une session de portail client
      const session = await stripe.billingPortal.sessions.create({
        customer: stripeCustomerID,
        return_url: baseURL, // Remplacez par l'URL de retour de votre application
      });

      return {
        url: session.url,
      };
    } catch (error) {
      console.error("Error creating Stripe customer portal session:", error);
      throw new functions.https.HttpsError(
        "internal",
        "Unable to create Stripe customer portal session."
      );
    }
  }
);
