import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache'; // ADD THIS
import { getPortals, savePortals } from '@/lib/db';
import { isValidHexColor, sanitizeWelcomeText } from '@/lib/sanitize';
import { validatePortal } from '@/lib/validation';
import { Portal } from '@/types';

export const dynamic = 'force-dynamic';

export async function GET() {
  const portals = await getPortals();
  return NextResponse.json(portals[0] || null);
}

export async function POST(request: Request) {
  try {
    const incomingPortal: Portal = await request.json();

    // Sanifica l'HTML del welcome text prima di validare la lunghezza, così il counter
    // riflette il contenuto effettivamente persistito.
    if (typeof incomingPortal.welcomeText === 'string') {
      incomingPortal.welcomeText = sanitizeWelcomeText(incomingPortal.welcomeText);
    }

    const { valid, errors } = validatePortal(incomingPortal);
    if (!valid) {
      return NextResponse.json({ error: 'Validation failed', errors }, { status: 400 });
    }

    // themeColor goes into a <style dangerouslySetInnerHTML> in PublicGrid,
    // so reject anything that is not a strict #RRGGBB.
    if (incomingPortal.themeColor !== undefined && !isValidHexColor(incomingPortal.themeColor)) {
      return NextResponse.json(
        { error: 'Validation failed', errors: [{ field: 'themeColor', message: 'Colore non valido (atteso #RRGGBB)' }] },
        { status: 400 }
      );
    }

    const portals = await getPortals();

    if (portals.length > 0) {
      portals[0] = { ...portals[0], ...incomingPortal };
    } else {
      portals.push({ ...incomingPortal, id: 'default-portal', tenantId: 'default' });
    }

    await savePortals(portals);

    // Rivalida sia la home che il layout (il font @font-face è applicato nel layout root)
    revalidatePath('/', 'layout');

    return NextResponse.json(portals[0], { status: 200 });
  } catch {
    return NextResponse.json({ error: 'Failed to save portal settings' }, { status: 500 });
  }
}