import { parseStringPromise } from 'xml2js'

export interface NotamItem {
  notamId: string
  title: string
  description: string
  link: string
  publishedAt: Date | null
  guid: string
}

export function extractNotamId(title: string): string {
  const match = title.match(/^([A-Z]\d{4}\/\d{2})/i)
  return match ? match[1].toUpperCase() : title
}

export async function parseNotamRss(xml: string): Promise<NotamItem[]> {
  const result = await parseStringPromise(xml, { explicitArray: false, trim: true })
  const items = result?.rss?.channel?.item
  if (!items) return []
  const arr = Array.isArray(items) ? items : [items]
  return arr.map((item: any) => ({
    notamId: extractNotamId(item.title ?? ''),
    title: item.title ?? '',
    description: item.description ?? '',
    link: item.link ?? '',
    publishedAt: item.pubDate ? new Date(item.pubDate) : null,
    guid: typeof item.guid === 'object' ? (item.guid._ ?? '') : (item.guid ?? ''),
  }))
}

const NOTAM_RSS_URL = process.env.NOTAM_RSS_URL ?? 'https://notaminfo.com/feed?u=ruijacome'

export async function fetchAndParseNotams(): Promise<NotamItem[]> {
  const res = await fetch(NOTAM_RSS_URL, {
    next: { revalidate: 7200 },
    headers: { Accept: 'application/rss+xml, application/xml, text/xml' },
  })
  if (!res.ok) throw new Error(`NOTAM RSS fetch failed: ${res.status}`)
  const xml = await res.text()
  return parseNotamRss(xml)
}
