import { fetchRawFeedXml } from './episodes.js'
import { getCanonicalBaseUrl } from '../email.js'

export function register(app) {
  app.get('/feed.xml', async (_req, res) => {
    try {
      const xml = await fetchRawFeedXml()
      if (!xml) {
        res.status(503).send('Feed temporarily unavailable')
        return
      }

      const baseUrl = getCanonicalBaseUrl().replace(/\/$/, '')
      const feedUrl = `${baseUrl}/feed.xml`

      // Rewrite channel <link> and <atom:link href> to our canonical domain
      const rewritten = xml
        .replace(
          /<atom:link[^>]+rel="self"[^>]*\/>/,
          `<atom:link href="${feedUrl}" rel="self" type="application/rss+xml"/>`
        )
        .replace(
          /(<channel>[\s\S]*?<link>)[^<]*(\/link>)/,
          `$1${baseUrl}$2`
        )

      res.set('Content-Type', 'application/rss+xml; charset=utf-8')
      res.set('Cache-Control', 'public, max-age=1800')
      res.send(rewritten)
    } catch (err) {
      console.error('[feed.xml]', err?.message ?? err)
      res.status(502).send('Failed to fetch feed')
    }
  })
}
