import { NextRequest, NextResponse } from 'next/server';
import { generateEphemeralToken } from '@/lib/gemini-live';

// ─── Rate Limiting ────────────────────────────────────────────────────────────

const rateLimitMap = new Map<string, number>();
const RATE_LIMIT_MS = 5_000; // 1 token per 5 seconds per IP

// ─── Health Check (GET — no rate limit) ──────────────────────────────────────

export async function GET() {
  if (!process.env.GEMINI_API_KEY) {
    return NextResponse.json({ success: false }, { status: 503 });
  }
  return NextResponse.json({ success: true });
}

// ─── Token Request (POST — rate limited) ─────────────────────────────────────

export async function POST(request: NextRequest) {
  try {
    if (!process.env.GEMINI_API_KEY) {
      return NextResponse.json({ success: false }, { status: 503 });
    }

    const ip =
      request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
      request.headers.get('x-real-ip') ??
      'unknown';

    const lastRequest = rateLimitMap.get(ip) ?? 0;
    if (Date.now() - lastRequest < RATE_LIMIT_MS) {
      return NextResponse.json({ success: false, error: 'Rate limited' }, { status: 429 });
    }
    rateLimitMap.set(ip, Date.now());

    const { locale } = (await request.json()) as { locale?: string };
    const supportedLocales = ['en', 'fr', 'it', 'es'];
    const result = generateEphemeralToken(supportedLocales.includes(locale ?? '') ? locale! : 'en');

    return NextResponse.json({
      success: true,
      apiKey: process.env.GEMINI_API_KEY,
      model: result.model,
      config: result.config,
    });
  } catch (error) {
    console.error('[gemini-token] Failed:', error);
    return NextResponse.json({ success: false }, { status: 500 });
  }
}
