import { createHmac } from 'crypto';

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { session_id } = req.body || {};
  if (!session_id) {
    return res.status(400).json({ error: 'Missing session_id' });
  }

  const stripeSecret = process.env.STRIPE_SECRET_KEY;
  if (!stripeSecret) {
    return res.status(500).json({ error: 'Server not configured' });
  }

  // Fetch checkout session from Stripe
  const sessionResp = await fetch(
    `https://api.stripe.com/v1/checkout/sessions/${encodeURIComponent(session_id)}`,
    { headers: { Authorization: `Bearer ${stripeSecret}` } }
  );
  if (!sessionResp.ok) {
    return res.status(400).json({ error: 'Invalid or expired session' });
  }

  const session = await sessionResp.json();
  const customerId = session.customer;
  if (!customerId) {
    return res.status(400).json({ error: 'No customer in session' });
  }

  // Determine plan from subscription price amount
  let plan = 'solo';
  if (session.subscription) {
    const subResp = await fetch(
      `https://api.stripe.com/v1/subscriptions/${session.subscription}`,
      { headers: { Authorization: `Bearer ${stripeSecret}` } }
    );
    if (subResp.ok) {
      const sub = await subResp.json();
      const amount = sub.items?.data?.[0]?.price?.unit_amount;
      if (amount >= 2500) plan = 'pro';
    }
  }

  // Generate HMAC-signed license key
  const payload = `${plan}:${customerId}`;
  const sig = createHmac('sha256', stripeSecret)
    .update(payload).digest('hex').slice(0, 24);
  const key = `PULSE-${plan.toUpperCase()}-${customerId}-${sig}`;

  return res.status(200).json({
    key,
    plan,
    instructions: [
      'pip install pulse-os',
      `pulse activate ${key}`,
      'pulse status',
    ],
  });
}
