import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';
import { getCards, saveCards } from '@/lib/db';
import { Card } from '@/types';

export const dynamic = 'force-dynamic';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const portalId = searchParams.get('portalId');
  const cards = await getCards(portalId || undefined);
  return NextResponse.json(cards);
}

export async function POST(request: Request) {
  try {
    const incomingCard: Card = await request.json();
    const cards = await getCards();
    const existingIndex = cards.findIndex(c => c.id === incomingCard.id);
    
    if (existingIndex >= 0) {
      cards[existingIndex] = incomingCard;
    } else {
      cards.push(incomingCard);
    }
    
    await saveCards(cards);
    revalidatePath('/'); // Force public portal to update instantly
    return NextResponse.json(incomingCard, { status: 200 });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to save card' }, { status: 500 });
  }
}

// NEW: Bulk update for saving card reordering
export async function PUT(request: Request) {
  try {
    const updatedCards: Card[] = await request.json();
    await saveCards(updatedCards);
    revalidatePath('/'); // Force public portal to update instantly
    return NextResponse.json({ success: true }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to reorder cards' }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    
    if (!id) return NextResponse.json({ error: 'Card ID required' }, { status: 400 });

    const cards = await getCards();
    const filteredCards = cards.filter(c => c.id !== id);
    
    await saveCards(filteredCards);
    revalidatePath('/'); // Force public portal to update instantly
    return NextResponse.json({ success: true }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to delete card' }, { status: 500 });
  }
}	