import { NextRequest, NextResponse } from 'next/server';
import { createTrialLicence } from '@/lib/supabase';

// In-memory IP rate limit: max 3 trials per IP per 24h
const ipWindows = new Map<string, { count: number; resetAt: number }>();

function checkIpLimit(ip: string): boolean {
  const now = Date.now();
  const win  = ipWindows.get(ip);
  if (!win || now > win.resetAt) {
    ipWindows.set(ip, { count: 1, resetAt: now + 24 * 60 * 60 * 1000 });
    return true;
  }
  if (win.count >= 3) return false;
  win.count++;
  return true;
}

async function sendTrialEmail(email: string, key: string) {
  const apiKey = process.env.RESEND_API_KEY;
  if (!apiKey) return;
  await fetch('https://api.resend.com/emails', {
    method:  'POST',
    headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      from:    'NoteToQuote <noreply@notetoquote.com>',
      to:      [email],
      subject: "Votre clé d'essai NoteToQuote (5 générations)",
      html: `<h2>Bienvenue sur NoteToQuote !</h2>
<p>Votre clé d'essai gratuit (5 générations) :</p>
<pre style="background:#f4f4f4;padding:1rem;border-radius:8px;font-size:1.2rem;letter-spacing:0.1em">${key}</pre>
<p>Installez le module dans Dolibarr → Configuration → NoteToQuote → coller la clé.</p>
<p>Des questions ? Répondez à cet email.</p>`,
    }),
  }).catch(console.error);
}

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

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

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

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

  const normalizedEmail = email.trim().toLowerCase();

  try {
    const { key } = await createTrialLicence(normalizedEmail);
    await sendTrialEmail(normalizedEmail, key);
    return NextResponse.json({ key });
  } catch (err: unknown) {
    const e = err as { code?: string; message?: string };
    if (e.code === 'already_exists') {
      return NextResponse.json({ error: 'already_exists' }, { status: 409 });
    }
    console.error('Trial creation error:', e.message);
    return NextResponse.json({ error: 'internal_error' }, { status: 500 });
  }
}
