import { NextResponse } from 'next/server'

const ANAC_ED318_URL = 'https://dnt.anac.pt/ED-318_json/UASZoneVersion%20ED-318%2022042026083042.json'

export async function GET() {
  try {
    const res = await fetch(ANAC_ED318_URL, { headers: { Accept: 'application/json' }, cache: 'no-store' })
    if (!res.ok) return NextResponse.json({ error: `upstream ${res.status}` }, { status: 502 })
    const raw = await res.json()

    const isArray = Array.isArray(raw)
    const topKeys = isArray ? ['(array)'] : Object.keys(raw)
    const arr = isArray ? raw : (raw?.[topKeys[0]] ?? null)
    const count = Array.isArray(arr) ? arr.length : '?'
    const firstItem = Array.isArray(arr) ? arr[0] : null

    return NextResponse.json({ topKeys, isArray, count, firstItem })
  } catch (err: any) {
    return NextResponse.json({ error: String(err) }, { status: 500 })
  }
}
