import { prisma } from '@/lib/db';
import { currentUser } from '@/lib/auth';
import { planById } from '@/lib/plans';
import { startCheckout, CheckoutError } from '@/lib/checkout';
import { payWithCredit } from '@/lib/orders';
import { appUrl } from '@/lib/http';
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  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 });
  const { id } = await params;
  const o = await prisma.order.findUnique({ where: { id } });
  if (!o || o.userId !== u.id) return Response.json({ error: 'Bulunamadı' }, { status: 404 });
  if (o.status !== 'PENDING_PAYMENT') return Response.json({ error: 'Bu sipariş için ödeme gerekmiyor' }, { status: 409 });
  if (await payWithCredit(u.id, o.id)) return Response.json({ redirect: `/panel/siparisler/${o.id}` });
  try { return Response.json({ redirect: await startCheckout(u, planById(o.plan) ?? planById('tek')!, appUrl(req), o.id) }); }
  catch (e) { return Response.json({ error: (e as Error).message }, { status: e instanceof CheckoutError ? e.status : 502 }); }
}
