import { NextResponse } from 'next/server'
import { fetchAndParseNotams } from '@/lib/notam'
import { prisma } from '@/lib/prisma'

export const revalidate = 7200

export async function GET() {
  // Try DB cache first
  try {
    const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000)
    const cached = await prisma.notam.findMany({
      where: { updatedAt: { gte: twoHoursAgo } },
      orderBy: { createdAt: 'desc' },
      take: 50,
    })
    if (cached.length > 0) {
      return NextResponse.json({ notams: cached }, { headers: { 'Cache-Control': 'public, s-maxage=7200' } })
    }
  } catch (dbErr) {
    console.error('NOTAM DB error (falling back to RSS):', dbErr)
  }

  // Direct RSS fetch
  try {
    const items = await fetchAndParseNotams()
    const notams = items.map((item) => ({
      id: item.guid || item.notamId,
      notamId: item.notamId,
      title: item.title,
      description: item.description,
    }))

    // Try to persist to DB (non-fatal if it fails)
    try {
      await Promise.all(
        items.map((item) =>
          prisma.notam.upsert({
            where: { notamId: item.notamId },
            update: { title: item.title, description: item.description, rawXml: item.link, validFrom: item.publishedAt },
            create: { notamId: item.notamId, title: item.title, description: item.description, rawXml: item.link, validFrom: item.publishedAt },
          })
        )
      )
    } catch {}

    return NextResponse.json({ notams }, { headers: { 'Cache-Control': 'public, s-maxage=7200' } })
  } catch (rssErr) {
    console.error('NOTAM RSS error:', rssErr)
    return NextResponse.json({ notams: [] })
  }
}
