const Stripe = require("stripe");
const { Companies, Subscriptions } = require("../models");

/**
 * Build Stripe Checkout session URL for a company's current subscription pricing.
 */
async function buildCheckoutSessionUrl(companyId) {
  const company = await Companies.findByPk(companyId);
  if (!company) throw new Error("Company not found");

  const subscription = await Subscriptions.findOne({
    where: { CompanyId: companyId },
    order: [["createdAt", "DESC"]],
  });
  if (!subscription) throw new Error("Subscription not found");

  if (
    subscription.userPrice == null ||
    subscription.projectPrice == null ||
    subscription.SDSSavePrice == null ||
    subscription.SDSSearchPerSavePrice == null
  ) {
    throw new Error("Subscription prices not fully set");
  }

  const price =
    subscription.usersCount * subscription.userPrice +
    subscription.projectsCount * subscription.projectPrice +
    subscription.monthlySDSSaveCount * subscription.SDSSavePrice +
    subscription.monthlySDSSaveCount * subscription.SDSSearchPerSavePrice;

  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: "NordSafe EHS Subscription",
          },
          unit_amount: Math.round(price * 100),
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: `${process.env.FRONTEND_URL}/company-settings/subscription?success=true`,
    cancel_url: `${process.env.FRONTEND_URL}/company-settings/subscription?canceled=true`,
    customer_email: company.email || undefined,
    metadata: {
      companyId: String(company.id),
    },
  });

  return session.url;
}

module.exports = { buildCheckoutSessionUrl };
