import { NextResponse } from 'next/server'

export async function GET() {
    try {
        const strapiBaseUrl = process.env.NEXT_PUBLIC_STRAPI_BASE_URL || process.env.NEW_STRAPI_URL
        // Fetch heading/description from whyschoolforschool and cards (with SVG) from fixed-cards
        const [whyRes, cardsRes] = await Promise.all([
            fetch(`${strapiBaseUrl}/api/whyschoolforschools?pagination[pageSize]=1`, {
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                    'Accept': 'application/json'
                },
                next: { revalidate: 60 }
            }),
            fetch(`${strapiBaseUrl}/api/fixed-cards?populate=*`, {
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                    'Accept': 'application/json'
                },
                next: { revalidate: 60 }
            })
        ])

        if (!whyRes.ok) throw new Error(`Why response ${whyRes.status}`)
        if (!cardsRes.ok) throw new Error(`Cards response ${cardsRes.status}`)

        const whyJson = await whyRes.json()
        const cardsJson = await cardsRes.json()

        // Normalize whyschoolforschool (supports v4 attributes or direct data)
        const firstWhy = Array.isArray(whyJson?.data)
            ? (whyJson.data[0]?.attributes ?? whyJson.data[0])
            : (whyJson?.data?.attributes ?? whyJson?.data)

        const heading = firstWhy?.heading ?? 'Why SFS'
        const description =
            firstWhy?.description ??
            'We combine expertise in education with cutting-edge technology to deliver solutions that truly make a difference.'

        // Normalize cards array
        const cards = Array.isArray(cardsJson?.data)
            ? cardsJson.data.map((item: any) => item?.attributes ?? item ?? {})
            : []

        return NextResponse.json({ heading, description, cards })
    } catch (error) {
        console.error('Error fetching WhySFS data:', error)
        return NextResponse.json({ error: 'Failed to fetch data' }, { status: 500 })
    }
}
