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

// GET active landing page (returns default if available, otherwise first active)
export async function GET(request: NextRequest) {
  try {
    // First try to get the default landing page
    let landingPage = await db.landingPage.findFirst({
      where: { 
        isDefault: true,
        isActive: true 
      }
    })

    // If no default found, get the first active landing page
    if (!landingPage) {
      landingPage = await db.landingPage.findFirst({
        where: { isActive: true },
        orderBy: { createdAt: 'asc' }
      })
    }

    // If still no active page, return a fallback
    if (!landingPage) {
      return NextResponse.json({
        success: false,
        error: 'No active landing page found',
        fallback: {
          type: 'CLASSIC',
          path: '/page'
        }
      }, { status: 404 })
    }

    return NextResponse.json({
      success: true,
      data: landingPage
    })
  } catch (error) {
    console.error('Error fetching active landing page:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch active landing page' },
      { status: 500 }
    )
  }
}