import "server-only";
import Stripe from "stripe";

/**
 * Wrapper Stripe.
 *
 * - Si `STRIPE_SECRET_KEY` est vide, `getStripe()` renvoie null. Les helpers
 *   gèrent ce cas en renvoyant `{ url: null }` pour permettre au formulaire
 *   public de basculer automatiquement sur le mode "virement".
 * - On utilise Stripe Checkout (page hostée par Stripe) plutôt qu'Elements,
 *   pour minimiser la surface PCI à notre charge.
 */

let cachedStripe: Stripe | null = null;
let initialized = false;

export function getStripe(): Stripe | null {
  if (initialized) return cachedStripe;
  initialized = true;

  const key = process.env.STRIPE_SECRET_KEY;
  if (!key || key.length < 10) {
    cachedStripe = null;
    return null;
  }
  cachedStripe = new Stripe(key, {
    apiVersion: "2026-04-22.dahlia",
    typescript: true,
  });
  return cachedStripe;
}

export function isStripeConfigured(): boolean {
  return getStripe() !== null;
}

export interface CheckoutInput {
  /** Référence dossier humaine (D-2025-0001). */
  dossierReference: string;
  /** UUID du dossier. */
  dossierId: string;
  /** UUID de la facture (acompte ou solde). */
  invoiceId: string;
  /** Numéro facture humain (F-2025-0001). */
  invoiceNumber: string;
  /** Libellé affiché côté Stripe (ex: "Acompte création de société"). */
  label: string;
  /** Montant en centimes EUR. */
  amountCents: number;
  /** Email du client (pré-rempli sur Stripe). */
  customerEmail: string;
  /** URL absolue vers `/societes/merci?session_id={CHECKOUT_SESSION_ID}`. */
  successUrl: string;
  /** URL absolue de retour si annulé. */
  cancelUrl: string;
}

/**
 * Crée une Checkout Session Stripe pour le paiement d'une facture.
 * Renvoie l'URL hostée par Stripe.
 *
 * Si Stripe n'est pas configuré, renvoie { url: null, sessionId: null }
 * et le caller doit basculer sur le mode virement.
 */
export async function createCheckoutSession(
  input: CheckoutInput
): Promise<{ url: string | null; sessionId: string | null }> {
  const stripe = getStripe();
  if (!stripe) return { url: null, sessionId: null };

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    payment_method_types: ["card"],
    customer_email: input.customerEmail,
    line_items: [
      {
        price_data: {
          currency: "eur",
          unit_amount: input.amountCents,
          product_data: {
            name: input.label,
            description: `Dossier ${input.dossierReference} · Facture ${input.invoiceNumber}`,
          },
        },
        quantity: 1,
      },
    ],
    metadata: {
      dossierId: input.dossierId,
      invoiceId: input.invoiceId,
      invoiceNumber: input.invoiceNumber,
    },
    success_url: input.successUrl,
    cancel_url: input.cancelUrl,
    locale: "fr",
  });

  return { url: session.url, sessionId: session.id };
}
