import type { Metadata } from 'next';
import { API_BASE, SITE_URL } from '@/lib/config';
import { articleJsonLd, breadcrumbJsonLd, absoluteUrl } from '@/lib/seo';
import ContentDetailClient from './client';

async function getContent(id: string) {
  try {
    const res = await fetch(`${API_BASE}/contents/${id}`, { next: { revalidate: 3600 } });
    if (!res.ok) return null;
    const data = await res.json();
    if (!data || !data.id) return null;
    return data;
  } catch {
    return null;
  }
}

export async function generateStaticParams() {
  try {
    const res = await fetch(`${API_BASE}/contents`);
    const data = await res.json();
    const items = data.items || [];
    if (items.length === 0) return [{ id: '1' }];
    return items.map((c: any) => ({ id: String(c.id) }));
  } catch {
    return [{ id: '1' }];
  }
}

export async function generateMetadata({ params }: { params: { id: string } }): Promise<Metadata> {
  const content = await getContent(params.id);
  if (!content) return { title: '文章未找到' };
  const title = content.title;
  const description = content.summary || content.content?.slice(0, 120) || `${content.title} - 宇之然 AI 文章`;
  const url = absoluteUrl(`/contents/${content.id}`);
  return {
    title,
    description,
    alternates: { canonical: `/contents/${content.id}` },
    openGraph: { type: 'article', title, description, url },
  };
}

export default async function ContentDetailPage({ params }: { params: { id: string } }) {
  const content = await getContent(params.id);
  const url = absoluteUrl(`/contents/${params.id}`);
  const jsonLd = content
    ? [
        articleJsonLd({
          headline: content.title,
          description: content.summary || undefined,
          url,
          datePublished: content.publishedAt || content.createdAt,
        }),
        breadcrumbJsonLd([
          { name: '首页', url: SITE_URL },
          { name: '文章', url: absoluteUrl('/contents') },
          { name: content.title, url },
        ]),
      ]
    : null;

  return (
    <>
      {jsonLd && (
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
      )}
      <ContentDetailClient initialContent={content} />
    </>
  );
}
