import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseAdmin, generateLicenceKey, hashKey } from '@/lib/supabase';
import { stripe } from '@/lib/stripe';
import { checkAdminLimit, checkAuth, getClientIp } from '@/lib/admin-auth';

export async function PATCH(
  req: NextRequest,
  ctx: { params: Promise<{ id: string }> }
) {
  const ip = getClientIp(req);
  if (!checkAdminLimit(ip)) return NextResponse.json({ error: 'rate_limit' }, { status: 429 });
  if (!checkAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 });

  const { id } = await ctx.params;

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

  const update: Record<string, boolean> = {};
  for (const field of ['active', 'flagged'] as const) {
    if (field in body && typeof (body as Record<string, unknown>)[field] === 'boolean') {
      update[field] = (body as Record<string, boolean>)[field];
    }
  }

  if (Object.keys(update).length === 0) {
    return NextResponse.json({ error: 'no_valid_fields' }, { status: 400 });
  }

  const { error } = await getSupabaseAdmin()
    .from('licences')
    .update(update)
    .eq('id', id);

  if (error) return NextResponse.json({ error: 'db_error' }, { status: 500 });
  return NextResponse.json({ ok: true });
}

export async function POST(
  req: NextRequest,
  ctx: { params: Promise<{ id: string }> }
) {
  const ip = getClientIp(req);
  if (!checkAdminLimit(ip)) return NextResponse.json({ error: 'rate_limit' }, { status: 429 });
  if (!checkAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 });

  const { id } = await ctx.params;

  const { data: licence } = await getSupabaseAdmin()
    .from('licences')
    .select('email')
    .eq('id', id)
    .single();

  if (!licence) return NextResponse.json({ error: 'not_found' }, { status: 404 });

  const key     = generateLicenceKey();
  const keyHash = hashKey(key);

  const { error } = await getSupabaseAdmin()
    .from('licences')
    .update({ key_hash: keyHash })
    .eq('id', id);

  if (error) return NextResponse.json({ error: 'db_error' }, { status: 500 });

  const apiKey = process.env.RESEND_API_KEY;
  if (apiKey) {
    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:      [licence.email],
        subject: 'Votre nouvelle clé de licence NoteToQuote',
        html: `<h2>Votre clé de licence a été régénérée</h2>
<p>Voici votre nouvelle clé de licence NoteToQuote :</p>
<p style="font-size:24px;font-weight:bold;font-family:monospace;letter-spacing:0.1em">${key}</p>
<p>Rendez-vous dans Dolibarr → NoteToQuote → Configuration pour la mettre à jour.</p>
<p style="color:#888;font-size:12px">L'ancienne clé ne fonctionnera plus.</p>`,
      }),
    }).catch(() => null);
  }

  return NextResponse.json({ key, email: licence.email });
}

export async function DELETE(
  req: NextRequest,
  ctx: { params: Promise<{ id: string }> }
) {
  const ip = getClientIp(req);
  if (!checkAdminLimit(ip)) return NextResponse.json({ error: 'rate_limit' }, { status: 429 });
  if (!checkAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 });

  const { id } = await ctx.params;

  const { data: licence } = await getSupabaseAdmin()
    .from('licences')
    .select('stripe_subscription_id')
    .eq('id', id)
    .single();

  if (licence?.stripe_subscription_id) {
    try {
      await stripe.subscriptions.cancel(licence.stripe_subscription_id);
    } catch {
      // sub may already be canceled — continue with deletion
    }
  }

  const { error } = await getSupabaseAdmin()
    .from('licences')
    .delete()
    .eq('id', id);

  if (error) return NextResponse.json({ error: 'db_error' }, { status: 500 });
  return NextResponse.json({ ok: true });
}
