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 { key } = req.body || {};
  if (!key) {
    return res.status(400).json({ error: 'Missing key' });
  }

  // Parse: PULSE-{PLAN}-{cus_id}-{sig}
  const parts = key.split('-');
  if (parts.length < 4 || parts[0] !== 'PULSE') {
    return res.status(400).json({ error: 'Invalid format' });
  }
  const plan = parts[1].toLowerCase();
  const customerId = parts[2];
  const sig = parts.slice(3).join('-');

  if (!['solo', 'pro'].includes(plan) || !customerId.startsWith('cus_')) {
    return res.status(400).json({ error: 'Invalid key' });
  }

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

  // Verify HMAC signature
  const payload = `${plan}:${customerId}`;
  const expected = createHmac('sha256', stripeSecret)
    .update(payload).digest('hex').slice(0, 24);
  if (sig !== expected) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  // Check Stripe subscription status — prefer active/trialing, accept past_due
  const VALID_STATUSES = ['active', 'trialing', 'past_due'];
  try {
    let foundSub = null;
    for (const status of VALID_STATUSES) {
      const resp = await fetch(
        `https://api.stripe.com/v1/subscriptions?customer=${encodeURIComponent(customerId)}&status=${status}&limit=1`,
        { headers: { Authorization: `Bearer ${stripeSecret}` } }
      );
      if (!resp.ok) return res.status(502).json({ error: 'Stripe error' });
      const data = await resp.json();
      if (data.data?.[0]) { foundSub = data.data[0]; break; }
    }

    if (!foundSub) {
      return res.status(200).json({ valid: false, plan, status: 'no_subscription' });
    }

    return res.status(200).json({
      valid: true,
      plan,
      status: foundSub.status,
      trial_end: foundSub.trial_end ?? null,
    });
  } catch {
    return res.status(502).json({ error: 'Failed to reach Stripe' });
  }
}
