import { createFileRoute } from '@tanstack/react-router'
import { getRobotsConfig } from '@/lib/robots'

function renderRobotsTxt() {
  const robots = getRobotsConfig()
  const lines = robots.rules.flatMap((rule) => [
    `User-agent: ${rule.userAgent}`,
    `Allow: ${rule.allow}`,
    ...(rule.disallow ?? []).map((path) => `Disallow: ${path}`),
  ])

  lines.push(`Sitemap: ${robots.sitemap}`)
  lines.push(`Host: ${robots.host}`)

  return `${lines.join('\n')}\n`
}

export const Route = createFileRoute('/robots.txt')({
  server: {
    handlers: {
      GET: async () =>
        new Response(renderRobotsTxt(), {
          headers: {
            'content-type': 'text/plain; charset=utf-8',
          },
        }),
    },
  },
})
