import { createHmac } from 'crypto';

const ACTIVE_STATUSES = ['active', 'trialing', 'past_due'];

function generateOTP(secret, email, window) {
  return createHmac('sha256', secret)
    .update(`${email.toLowerCase().trim()}:${window}`)
    .digest('hex')
    .slice(0, 6)
    .toUpperCase();
}

function verifyOTP(secret, email, code) {
  const now = Math.floor(Date.now() / 1000 / 300);
  // Accept current window and previous (handles edge case at window boundary)
  return (
    generateOTP(secret, email, now) === code.toUpperCase().trim() ||
    generateOTP(secret, email, now - 1) === code.toUpperCase().trim()
  );
}

async function fetchJson(url, stripeSecret) {
  const resp = await fetch(url, {
    headers: { Authorization: `Bearer ${stripeSecret}` },
  });
  if (!resp.ok) return null;
  return resp.json();
}

async function getActiveSub(customerId, stripeSecret) {
  for (const status of ACTIVE_STATUSES) {
    const data = await fetchJson(
      `https://api.stripe.com/v1/subscriptions?customer=${customerId}&status=${status}&limit=1`,
      stripeSecret
    );
    if (data?.data?.[0]) return data.data[0];
  }
  const canceled = await fetchJson(
    `https://api.stripe.com/v1/subscriptions?customer=${customerId}&status=canceled&limit=1`,
    stripeSecret
  );
  return canceled?.data?.[0] ?? null;
}

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

  const { email, code } = req.body || {};
  if (!email || !email.includes('@')) {
    return res.status(400).json({ error: 'Valid email required' });
  }
  if (!code || code.length !== 6) {
    return res.status(400).json({ error: 'Valid 6-digit code required' });
  }

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

  // Verify OTP before touching Stripe
  if (!verifyOTP(otpSecret, email, code)) {
    return res.status(401).json({ error: 'Invalid or expired code. Request a new one.' });
  }

  // Look up customers by email (may have multiple)
  const searchData = await fetchJson(
    `https://api.stripe.com/v1/customers?email=${encodeURIComponent(email)}&limit=10`,
    stripeSecret
  );
  if (!searchData) {
    return res.status(500).json({ error: 'Could not reach billing provider' });
  }

  const customers = searchData.data ?? [];
  if (customers.length === 0) {
    return res.status(404).json({
      error: 'No account found for that email. Did you use a different email at checkout?',
    });
  }

  // Find the customer that has a subscription
  let foundCustomer = null;
  let foundSub = null;
  for (const customer of customers) {
    const sub = await getActiveSub(customer.id, stripeSecret);
    if (sub) {
      foundCustomer = customer;
      foundSub = sub;
      break;
    }
  }

  if (!foundCustomer || !foundSub) {
    return res.status(404).json({
      error: 'No subscription found for that email. Contact hello@pulseos.dev if you believe this is an error.',
    });
  }

  const amount = foundSub.items?.data?.[0]?.price?.unit_amount;
  const plan = amount >= 2500 ? 'pro' : 'solo';

  const payload = `${plan}:${foundCustomer.id}`;
  const sig = createHmac('sha256', stripeSecret)
    .update(payload).digest('hex').slice(0, 24);
  const key = `PULSE-${plan.toUpperCase()}-${foundCustomer.id}-${sig}`;

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