import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const location = searchParams.get('location'); // 'navigation', 'footer', or 'all'

    const where: any = {
      status: 'PUBLISHED'
    };

    if (location === 'navigation') {
      where.showInNavigation = true;
    } else if (location === 'footer') {
      where.showInFooter = true;
    }

    const orderBy: any = [];
    if (location === 'navigation') {
      orderBy.push({ navigationOrder: 'asc' });
    } else if (location === 'footer') {
      orderBy.push({ footerOrder: 'asc' });
    }
    orderBy.push({ title: 'asc' });

    const pages = await prisma.page.findMany({
      where,
      orderBy,
      select: {
        id: true,
        title: true,
        slug: true,
        excerpt: true,
        showInNavigation: true,
        showInFooter: true,
        navigationOrder: true,
        footerOrder: true
      }
    });

    return NextResponse.json({
      success: true,
      data: pages
    });
  } catch (error) {
    console.error('Error fetching public pages:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch pages' },
      { status: 500 }
    );
  }
}