import type { APIRoute } from 'astro'

import { api, DEFAULT_SITE_SETTINGS } from '../lib/api/client'

export const prerender = false

export const GET: APIRoute = async ({ request }) => {
  const fallbackOrigin = new URL(request.url).origin

  let siteUrl = DEFAULT_SITE_SETTINGS.siteUrl
  try {
    const settings = await api.getSiteSettings()
    siteUrl = settings.siteUrl || siteUrl
  } catch {
    siteUrl = DEFAULT_SITE_SETTINGS.siteUrl
  }

  const base = (siteUrl || fallbackOrigin).replace(/\/$/, '')

  const body = `User-agent: *
Allow: /
Disallow: /admin
Disallow: /search
Disallow: /subscriptions/

User-agent: Googlebot
Allow: /

User-agent: Bingbot
Allow: /

User-agent: OAI-SearchBot
Allow: /

User-agent: GPTBot
Allow: /

User-agent: PerplexityBot
Allow: /

Sitemap: ${base}/sitemap.xml
`

  return new Response(body, {
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      'Cache-Control': 'public, max-age=600',
    },
  })
}
