import { prisma } from '@/lib/db';
import { currentUser } from '@/lib/auth';
import { newApiKey } from '@/lib/apiAuth';
import { rateLimit } from '@/lib/http';
export const dynamic = 'force-dynamic';

/** B2B API anahtarı üretir (eskisini geçersiz kılar). Anahtar yalnızca bu yanıtta tam görünür. */
export async function POST() {
  const u = await currentUser(); if (!u) return Response.json({ error: 'Giriş gerekli' }, { status: 401 });
  if (!u.emailVerifiedAt) return Response.json({ error: 'Önce e-posta doğrulayın' }, { status: 403 });
  if (!await rateLimit(`apikey:${u.id}`, 10, 60 * 60_000)) return Response.json({ error: 'Çok fazla istek' }, { status: 429 });
  const key = newApiKey();
  await prisma.user.update({ where: { id: u.id }, data: { apiKey: key } });
  return Response.json({ key });
}

export async function DELETE() {
  const u = await currentUser(); if (!u) return Response.json({ error: 'Giriş gerekli' }, { status: 401 });
  await prisma.user.update({ where: { id: u.id }, data: { apiKey: null } });
  return Response.json({ ok: true });
}
