// app/api/homepage-content/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getHomepageContent, saveHomepageContent } from '@/lib/homepage-content';
import { revalidatePath } from 'next/cache';

// GET — return current Puck data
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const path = searchParams.get('path') ?? '/';
    const content = await getHomepageContent(path);
    return NextResponse.json(content);
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch content' },
      { status: 500 }
    );
  }
}

// POST — save Puck data
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const mode = body.mode || 'publish'; // 'publish', 'draft', or 'auto'
    const path = body.path || '/';

    // The editor sends { content: <Puck Data> }
    // We store it as { puckData: <Puck Data> } in the DB content column
    const puckData = body.content;
    const result = await saveHomepageContent({ puckData }, body.updatedBy, mode, path);

    if (result.success) {
      if (mode === 'publish') {
        revalidatePath(path); // Bust the correct live site cache
      }
      revalidatePath('/page_editor_admin'); // Always update editor cache
      return NextResponse.json({ success: true });
    }

    return NextResponse.json(
      { error: result.error || 'Failed to save' },
      { status: 500 }
    );
  } catch (error) {
    return NextResponse.json(
      { error: 'Invalid request body' },
      { status: 400 }
    );
  }
}
