import type { APIRoute } from 'astro'

import { api, DEFAULT_SITE_SETTINGS } from '../lib/api/client'
import { buildArticleHighlights, buildArticleSynopsis, resolvePostUpdatedAt } from '../lib/seo'

export const prerender = false

function normalizeBase(value: string) {
  return value.replace(/\/$/, '')
}

function absolute(base: string, path: string) {
  return `${normalizeBase(base)}${path.startsWith('/') ? path : `/${path}`}`
}

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

  const [settingsResult, postsResult, categoriesResult, tagsResult, reviewsResult] = await Promise.allSettled([
    api.getSiteSettings(),
    api.getPosts(),
    api.getCategories(),
    api.getTags(),
    api.getReviews(),
  ])

  const siteSettings = settingsResult.status === 'fulfilled' ? settingsResult.value : DEFAULT_SITE_SETTINGS
  const posts = postsResult.status === 'fulfilled' ? postsResult.value.filter((item) => !item.noindex) : []
  const categories = categoriesResult.status === 'fulfilled' ? categoriesResult.value : []
  const tags = tagsResult.status === 'fulfilled' ? tagsResult.value : []
  const reviews = reviewsResult.status === 'fulfilled' ? reviewsResult.value : []
  const base = normalizeBase(siteSettings.siteUrl || fallbackOrigin)

  const body = [
    `# ${siteSettings.siteName} / full LLM catalog`,
    '',
    `Canonical homepage: ${base}/`,
    `Canonical sitemap: ${absolute(base, '/sitemap.xml')}`,
    `Canonical RSS: ${absolute(base, '/rss.xml')}`,
    '',
    '## About the site',
    `- Title: ${siteSettings.siteTitle}`,
    `- Description: ${siteSettings.siteDescription}`,
    `- Owner: ${siteSettings.ownerName}`,
    `- Owner role: ${siteSettings.ownerTitle}`,
    `- Tech stack: ${siteSettings.techStack.join(', ')}`,
    '',
    '## Categories',
    ...categories.flatMap((category) => [
      `- ${category.name}: ${absolute(base, `/categories/${encodeURIComponent(category.slug || category.name)}`)}`,
      `  ${category.description || category.seoDescription || `${category.name} related content.`}`,
    ]),
    '',
    '## Tags',
    ...tags.slice(0, 24).flatMap((tag) => [
      `- ${tag.name}: ${absolute(base, `/tags/${encodeURIComponent(tag.slug || tag.name)}`)}`,
      `  ${tag.description || tag.seoDescription || `${tag.name} topic hub.`}`,
    ]),
    '',
    '## Articles',
    ...posts.flatMap((post) => [
      `### ${post.title}`,
      `- URL: ${absolute(base, `/articles/${post.slug}`)}`,
      `- Category: ${post.category}`,
      `- Tags: ${post.tags.join(', ') || 'None'}`,
      `- Updated: ${resolvePostUpdatedAt(post)}`,
      `- Summary: ${buildArticleSynopsis(post, 220)}`,
      ...buildArticleHighlights(post, 3).map((item) => `- Highlight: ${item}`),
      '',
    ]),
    '## Reviews',
    ...reviews.slice(0, 24).flatMap((review) => [
      `- ${review.title}: ${absolute(base, `/reviews/${review.id}`)}`,
      `  ${review.description || 'Review detail page.'}`,
    ]),
    '',
    '## Canonical navigation',
    `- About: ${absolute(base, '/about')}`,
    `- Articles: ${absolute(base, '/articles')}`,
    `- Categories: ${absolute(base, '/categories')}`,
    `- Tags: ${absolute(base, '/tags')}`,
    `- Reviews: ${absolute(base, '/reviews')}`,
    `- Timeline: ${absolute(base, '/timeline')}`,
    `- Friends: ${absolute(base, '/friends')}`,
    ...(siteSettings.ai.enabled ? [`- Ask: ${absolute(base, '/ask')}`] : []),
  ].join('\n')

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