// 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 content = await getHomepageContent();
    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();

    // 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);

    if (result.success) {
      // Revalidate homepage and editor page so changes appear immediately
      revalidatePath('/');
      revalidatePath('/page_editor_admin');
      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 }
    );
  }
}
