import Stripe from "stripe";

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();

  if (!config.stripeSecretKey) {
    throw createError({
      statusCode: 500,
      message: "Stripe nicht konfiguriert – NUXT_STRIPE_SECRET_KEY fehlt",
    });
  }

  const stripe = new Stripe(config.stripeSecretKey);
  const user = await requireUser(event);

  const body = await readBody(event);
  const plan = body?.plan as string;
  const billing = (body?.billing as string) || "monthly";

  // Aktive Pläne: free (kein Checkout), pro, legend (legend noch nicht aktiv – TODO: Stripe-Preise hinzufügen)
  const activePlans = ["pro", "legend"];
  if (!plan || !activePlans.includes(plan)) {
    throw createError({ statusCode: 400, message: "Ungültiger Plan" });
  }
  if (!["monthly", "yearly"].includes(billing)) {
    throw createError({
      statusCode: 400,
      message: "Ungültiger Billing-Zyklus",
    });
  }

  const priceEnvMap: Record<string, Record<string, string>> = {
    pro: {
      monthly: "STRIPE_PRICE_STANDARD_MONTHLY",
      quarterly: "STRIPE_PRICE_STANDARD_QUARTERLY",
      yearly: "STRIPE_PRICE_STANDARD_YEARLY",
    },
    legend: {
      monthly: "STRIPE_PRICE_PRO_MONTHLY",
      quarterly: "STRIPE_PRICE_PRO_QUARTERLY",
      yearly: "STRIPE_PRICE_PRO_YEARLY",
    },
  };

  const envKey = priceEnvMap[plan][billing];
  const priceId = process.env[envKey];

  if (!priceId || !priceId.startsWith("price_")) {
    throw createError({
      statusCode: 503,
      message: `Dieser Plan ist noch nicht verfügbar. (${envKey} nicht gesetzt)`,
    });
  }

  const appUrl = config.public.appUrl || "https://rebreak.org";

  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: `${appUrl}/app/settings?upgraded=true`,
    cancel_url: `${appUrl}/pricing`,
    client_reference_id: user.id,
    metadata: {
      user_id: user.id,
      plan,
    },
  });

  return { url: session.url };
});
