/**
 * POST /api/checkout
 *
 * Creates a Stripe Checkout session and returns the URL
 * for the browser to redirect to.
 */

import type { Context } from "hono";
import type { Env } from "../env.d";
import Stripe from "stripe";

interface CheckoutRequest {
  plan: "individual" | "team" | "enterprise";
  email: string;
}

const VALID_PLANS = new Set(["individual", "team", "enterprise"]);
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export async function handleCheckout(c: Context): Promise<Response> {
  const env = c.env as Env;

  let body: CheckoutRequest;
  try {
    body = await c.req.json();
  } catch {
    return c.json({ error: "Invalid JSON body" }, 400);
  }

  if (!body.plan || !VALID_PLANS.has(body.plan)) {
    return c.json({ error: "Invalid plan. Must be: individual, team, or enterprise" }, 400);
  }
  if (!body.email?.trim()) {
    return c.json({ error: "email is required" }, 400);
  }
  if (!EMAIL_RE.test(body.email.trim())) {
    return c.json({ error: "Invalid email address" }, 400);
  }

  // Map plan to Stripe price ID
  const priceMap: Record<string, string> = {
    individual: env.STRIPE_PRICE_INDIVIDUAL,
    team: env.STRIPE_PRICE_TEAM,
    enterprise: env.STRIPE_PRICE_ENTERPRISE,
  };

  const priceId = priceMap[body.plan];
  if (!priceId) {
    return c.json({ error: `Price not configured for plan: ${body.plan}` }, 500);
  }

  const stripe = new Stripe(env.STRIPE_SECRET_KEY);

  try {
    const session = await stripe.checkout.sessions.create({
      mode: "payment",
      line_items: [{ price: priceId, quantity: 1 }],
      customer_email: body.email.trim(),
      metadata: { plan: body.plan },
      success_url: `${env.ALLOWED_ORIGIN}/success.html?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${env.ALLOWED_ORIGIN}/#pricing`,
    });

    return c.json({ url: session.url });
  } catch (err) {
    console.error("Stripe checkout error:", err);
    return c.json({ error: "Failed to create checkout session" }, 500);
  }
}
