import type { APIRoute } from "astro";
import { site } from "../data/site";
import { getPublishedArticles } from "../lib/articles";

export const prerender = true;

export const GET: APIRoute = async ({ site: configuredSite }) => {
  const articles = await getPublishedArticles();
  const origin = configuredSite ?? new URL("https://www.zhiyintec.com");
  const url = (pathname: string) => new URL(pathname, origin).href;
  const lines = [
    `# ${site.brand.name}（${site.brand.englishName}）完整站点内容`, "", `> ${site.brand.tagline}`, "",
    `官方网站：${url("/")}`, `企业主体：${site.brand.legalName}`, `咨询电话：${site.contact.phone}`, `联系邮箱：${site.contact.email}`, `公司地址：${site.contact.address}`, "",
    "## 品牌与服务概览", "", site.home.subhead, "", ...site.about.story, "",
    "## 核心能力数据", "", ...site.home.stats.map((stat) => `- ${stat.label}：${stat.value}`), "",
    "## 产品服务", "", `服务总览：${url("/services/")}`, "",
    ...site.services.flatMap((service) => [
      `### ${service.name}`, "", `页面：${url(`/services/${service.slug}/`)}`, "", service.intro, "", "服务特点：", ...service.features.map((feature) => `- ${feature}`), "", "核心能力：", ...service.capabilities.map((capability) => `- ${capability.label}：${capability.value}`), "",
    ]),
    "## 自研技术", "", ...site.about.technologies.map((technology) => `- ${technology}`), "",
    "## 服务闭环", "", ...site.workflow.map((step) => `- ${step.title}：${step.desc}`), "",
    "## 常见问题", "", `常见问题页面：${url("/faq/")}`, "", ...site.faq.flatMap((item) => [`### ${item.q}`, "", item.a, ""]),
    "## 洞察中心全文", "", ...articles.flatMap((article) => [`### ${article.data.title}`, "", `页面：${url(`/articles/${article.id}/`)}`, `分类：${article.data.category}`, `作者：${article.data.author}`, `发布日期：${article.data.date.toISOString().slice(0, 10)}`, `更新时间：${article.data.updated.toISOString().slice(0, 10)}`, "", article.data.excerpt, "", article.body, ""]),
    "## 联系方式", "", `联系页面：${url("/contact/")}`, `咨询电话：${site.contact.phone}`, `联系邮箱：${site.contact.email}`, `公司地址：${site.contact.address}`, `内容矩阵：${site.contact.socials.join("、")}`, "",
  ];
  return new Response(lines.join("\n"), { headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" } });
};
