import type { APIRoute } from 'astro'

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

export const prerender = false

function escapeXml(value: string) {
  return value
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&apos;')
}

function truncate(value: string, maxChars: number) {
  const trimmed = value.trim()
  if (trimmed.length <= maxChars) {
    return trimmed
  }
  return `${trimmed.slice(0, maxChars - 1)}…`
}

export const GET: APIRoute = async ({ params }) => {
  const slug = params.slug?.trim() || ''
  if (!slug) {
    return new Response('Missing slug', { status: 400 })
  }

  const [post, siteSettings] = await Promise.all([
    apiClient.getPostBySlug(slug),
    apiClient.getSiteSettings().catch(() => DEFAULT_SITE_SETTINGS),
  ])

  if (!post) {
    return new Response('Not found', { status: 404 })
  }

  const title = escapeXml(truncate(post.title, 72))
  const description = escapeXml(truncate(post.description || siteSettings.siteDescription, 120))
  const category = escapeXml(post.category || 'Article')
  const siteName = escapeXml(siteSettings.siteName || 'Termi')

  const svg = `<?xml version="1.0" encoding="UTF-8"?>
<svg width="1200" height="630" viewBox="0 0 1200 630" fill="none" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="bg" x1="0" y1="0" x2="1200" y2="630" gradientUnits="userSpaceOnUse">
      <stop stop-color="#08111f"/>
      <stop offset="1" stop-color="#0f1f35"/>
    </linearGradient>
    <linearGradient id="accent" x1="0" y1="0" x2="1200" y2="0" gradientUnits="userSpaceOnUse">
      <stop stop-color="#00ff9d"/>
      <stop offset="1" stop-color="#00b8ff"/>
    </linearGradient>
  </defs>
  <rect width="1200" height="630" fill="url(#bg)"/>
  <rect x="52" y="48" width="1096" height="534" rx="32" fill="#0D1117" stroke="rgba(255,255,255,0.12)"/>
  <rect x="52" y="48" width="1096" height="58" rx="32" fill="#111827"/>
  <circle cx="92" cy="77" r="10" fill="#FF5F56"/>
  <circle cx="124" cy="77" r="10" fill="#FFBD2E"/>
  <circle cx="156" cy="77" r="10" fill="#27C93F"/>
  <text x="190" y="83" fill="#9CA3AF" font-family="'JetBrains Mono', monospace" font-size="22">~/articles/${escapeXml(post.slug)}</text>
  <rect x="88" y="150" width="180" height="44" rx="22" fill="rgba(0,255,157,0.12)" stroke="url(#accent)"/>
  <text x="178" y="178" text-anchor="middle" fill="#8BFFD3" font-family="'JetBrains Mono', monospace" font-size="24">${category}</text>
  <text x="88" y="274" fill="#F8FAFC" font-family="'IBM Plex Sans', Arial, sans-serif" font-size="64" font-weight="700">${title}</text>
  <text x="88" y="358" fill="#CBD5E1" font-family="'IBM Plex Sans', Arial, sans-serif" font-size="32">${description}</text>
  <rect x="88" y="500" width="1024" height="2" fill="rgba(255,255,255,0.08)"/>
  <text x="88" y="548" fill="#00FF9D" font-family="'JetBrains Mono', monospace" font-size="28">${siteName}</text>
  <text x="1112" y="548" text-anchor="end" fill="#94A3B8" font-family="'JetBrains Mono', monospace" font-size="24">${escapeXml(post.date)}</text>
</svg>`

  return new Response(svg, {
    headers: {
      'Content-Type': 'image/svg+xml; charset=utf-8',
      'Cache-Control': 'public, max-age=3600',
    },
  })
}
