// server/routes/sitemap.xml.ts
import { defineEventHandler, createError } from 'h3'

const BASE_URL = 'https://www.heketai.com/'
const API_URL = 'https://www.ushopfy.cn/api/seller/spu/list'

// 缓存内容（24小时）
let cache = { xml: '', timestamp: 0 }
const CACHE_TTL = 24 * 60 * 60 * 1000 // 24小时
function escapeXml(str: string) {
  if (!str) return ''
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;')
}
export default defineEventHandler(async (event) => {
  // 命中缓存直接返回
  if (cache.xml && Date.now() - cache.timestamp < CACHE_TTL) {
    event.node.res.setHeader('Content-Type', 'application/xml')
    console.log('有缓存，直接返回')
    return cache.xml
  }

  // ---- 静态页面（每周更新） ----
  const staticPages = [
    { url: '/', priority: 1.0, changefreq: 'weekly' },
    { url: '/login', priority: 0.8, changefreq: 'weekly' },
    { url: '/register', priority: 0.8, changefreq: 'weekly' },
    { url: '/cooperate', priority: 0.7, changefreq: 'weekly' },
    { url: '/register/privacy', priority: 0.7, changefreq: 'yearly' },
    { url: '/register/agreement', priority: 0.7, changefreq: 'yearly' }
  ]

  

  // ---- 拼接所有 URL ----
  const allUrls = [...staticPages]

  // ---- 生成 XML ----
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:xhtml="http://www.w3.org/1999/xhtml"
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
${allUrls
      .map(
        (item: any) => `
  <url>
    <loc>${escapeXml(BASE_URL + item.url)}</loc>
    <changefreq>${item.changefreq}</changefreq>
    <priority>${item.priority}</priority>
    <lastmod>${new Date().toISOString()}</lastmod>
    ${item.image ? '<image:image><image:loc>' + escapeXml(item.image) + '</image:loc><image:title>' + escapeXml(item.title) + '</image:title><image:caption>' + escapeXml(item.caption) + '</image:caption></image:image>' : ''}
  </url>`
      )
      .join('')}
</urlset>`

  // ---- 写入缓存 ----
  cache.xml = xml
  cache.timestamp = Date.now()

  event.node.res.setHeader('Content-Type', 'application/xml')
  return xml
})
