import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache'; // ADD THIS
import { getPortals, savePortals } from '@/lib/db';
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();
    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);
    
    // ADD THIS LINE
    revalidatePath('/'); 
    
    return NextResponse.json(portals[0], { status: 200 });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to save portal settings' }, { status: 500 });
  }
}