import { NextRequest, NextResponse } from 'next/server';
import { stripe, PLANS, type PlanKey } from '@/lib/stripe';

// 10 checkout sessions per minute per IP
const ipWindows = new Map<string, { count: number; resetAt: number }>();
function checkLimit(ip: string): boolean {
  const now = Date.now();
  const win  = ipWindows.get(ip);
  if (!win || now > win.resetAt) {
    ipWindows.set(ip, { count: 1, resetAt: now + 60_000 });
    return true;
  }
  if (win.count >= 10) return false;
  win.count++;
  return true;
}

export async function POST(req: NextRequest) {
  const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? '0.0.0.0';
  if (!checkLimit(ip)) {
    return NextResponse.json({ error: 'rate_limit' }, { status: 429 });
  }

  const body = await req.json().catch(() => null);
  if (!body || typeof body !== 'object') {
    return NextResponse.json({ error: 'invalid_json' }, { status: 400 });
  }

  const { plan, email } = body as { plan?: unknown; email?: unknown };

  if (!plan || typeof plan !== 'string' || !PLANS[plan as PlanKey]) {
    return NextResponse.json({ error: 'invalid_plan' }, { status: 400 });
  }
  if (
    !email ||
    typeof email !== 'string' ||
    !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) ||
    email.length > 320
  ) {
    return NextResponse.json({ error: 'invalid_email' }, { status: 400 });
  }

  const planConfig = PLANS[plan as PlanKey];
  if (!planConfig.priceId) {
    return NextResponse.json({ error: 'plan_unavailable' }, { status: 503 });
  }
  const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? 'https://notetoquote.com';

  const session = await stripe.checkout.sessions.create({
    mode:                 'subscription',
    payment_method_types: ['card'],
    customer_email:       email,
    line_items: [{ price: planConfig.priceId, quantity: 1 }],
    subscription_data: {
      metadata: { plan, quota: String(planConfig.quota), email },
    },
    metadata:   { plan, email },
    success_url: `${appUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url:  `${appUrl}/cancel`,
    allow_promotion_codes: true,
  });

  return NextResponse.json({ url: session.url });
}
