import { currentUser } from '@/lib/auth';
import { planById } from '@/lib/plans';
import { startCheckout, CheckoutError } from '@/lib/checkout';
import { appUrl, rateLimit } from '@/lib/http';
export async function POST(req: Request) {
  const u = await currentUser(); if (!u) return Response.json({ error: 'Giriş gerekli' }, { status: 401 });
  if (!u.emailVerifiedAt) return Response.json({ error: 'Sipariş için önce e-posta adresinizi doğrulayın.' }, { status: 403 });
  if (!await rateLimit(`co:${u.id}`, 10, 60_000)) return Response.json({ error: 'Çok fazla istek' }, { status: 429 });
  const { plan } = await req.json().catch(() => ({}));
  const p = planById(String(plan)); if (!p) return Response.json({ error: 'Geçersiz paket' }, { status: 400 });
  try { return Response.json({ redirect: await startCheckout(u, p, appUrl(req)) }); }
  catch (e) { return Response.json({ error: (e as Error).message }, { status: e instanceof CheckoutError ? e.status : 502 }); }
}
