// app/api/recruiter/subscription/start/route.ts
import { NextResponse } from "next/server";
import Stripe from "stripe";
import { corePool } from "@/lib/db/mysql";

/**
 * ENV requis:
 * - STRIPE_SECRET_KEY
 * - APP_URL (ex: http://localhost:3000)
 * - STRIPE_PRICE_SENIOR_READY_MONTHLY (price_xxx)
 * - STRIPE_PRICE_SENIOR_READY_YEARLY (price_xxx)
 *
 * Notes:
 * - On ne publie rien ici.
 * - On crée une Checkout Session "subscription".
 * - L’activation réelle se fait UNIQUEMENT via webhook.
 */

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2023-10-16",
});

type PlanBilling = "monthly" | "yearly";

export async function POST(req: Request) {
  try {
    const body = await req.json();

    // Dans ta vraie app: company_id doit venir du recruteur authentifié (session/JWT).
    // Ici on reste volontairement simple et explicite.
    const company_id = Number(body?.company_id);
    const billing: PlanBilling = body?.billing === "yearly" ? "yearly" : "monthly";

    if (!company_id) {
      return NextResponse.json(
        { error: "missing_company_id" },
        { status: 400 }
      );
    }

    // Vérifie entreprise
    const [[company]]: any = await corePool.query(
      `SELECT id, name, plan_type, plan_status FROM companies WHERE id = ? LIMIT 1`,
      [company_id]
    );

    if (!company) {
      return NextResponse.json({ error: "company_not_found" }, { status: 404 });
    }

    // Tu peux autoriser le démarrage même si plan_status != active (upgrade),
    // mais on peut bloquer si suspended selon ta politique.
    if (company.plan_status === "suspended") {
      return NextResponse.json(
        { error: "company_suspended" },
        { status: 403 }
      );
    }

    const monthlyPrice = process.env.STRIPE_PRICE_SENIOR_READY_MONTHLY;
    const yearlyPrice = process.env.STRIPE_PRICE_SENIOR_READY_YEARLY;

    if (!monthlyPrice || !yearlyPrice) {
      return NextResponse.json(
        { error: "missing_stripe_prices" },
        { status: 500 }
      );
    }

    const priceId = billing === "yearly" ? yearlyPrice : monthlyPrice;

    // Optionnel: retrouver/forcer un customer Stripe existant si tu le stockes côté DB.
    // Ici: Stripe créera un customer via email si tu le fournis. Sans email, il crée quand même.
    // Si tu as un champ companies.billing_email, tu peux l’ajouter.
    // const billing_email = company.billing_email ?? undefined;

    const session = await stripe.checkout.sessions.create({
      mode: "subscription",
      payment_method_types: ["card"],
      line_items: [{ price: priceId, quantity: 1 }],
      // customer_email: billing_email,

      // IMPORTANT: metadata pour rattacher le webhook à l’entreprise
      metadata: {
        company_id: String(company.id),
        intent: "senior_ready_subscription",
        billing: billing,
      },

      success_url: `${process.env.APP_URL}/recruteur/abonnement/success`,
      cancel_url: `${process.env.APP_URL}/recruteur/abonnement/cancel`,
    });

    return NextResponse.json({ url: session.url });
  } catch (err) {
    console.error("subscription start error:", err);
    return NextResponse.json(
      { error: "internal_error" },
      { status: 500 }
    );
  }
}
