import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { BLOG_POSTS, BlogPost } from "@/content/blog";
import { blogService } from "@/lib/blog-service";
import { BlogCategoryView } from "@/components/blog/blog-category-view";
import { BLOG_CATEGORIES_LIST } from "@/lib/blog-categories-data";
import { JsonLd } from "@/components/json-ld";
import { site, ogBase, twitterBase } from "@/content/site";

export const revalidate = 60;

interface CategoryPageProps {
  params: Promise<{ category: string }>;
}

export function generateStaticParams() {
  return BLOG_CATEGORIES_LIST.map((c) => ({
    category: c.slug,
  }));
}

export async function generateMetadata({
  params,
}: CategoryPageProps): Promise<Metadata> {
  const { category } = await params;
  const info = BLOG_CATEGORIES_LIST.find((c) => c.slug === category);
  if (!info) {
    return { title: "Category not found", robots: { index: false, follow: false } };
  }

  // Mirror the XML sitemap's gating (sitemap.ts only lists category URLs when
  // published posts exist): don't let an empty/thin category listing be indexed.
  let hasPublishedPosts = false;
  try {
    const published = await blogService.getPublishedPosts({ limit: 1 });
    hasPublishedPosts = Boolean(published && published.length > 0);
  } catch {}

  const title = `${info.title} Guides & Articles — Quto AI Blog`;

  return {
    title: { absolute: title },
    description: info.description,
    alternates: { canonical: `/blog/category/${info.slug}` },
    robots: hasPublishedPosts ? undefined : { index: false, follow: true },
    openGraph: {
      ...ogBase,
      title,
      description: info.description,
      url: `/blog/category/${info.slug}`,
    },
    twitter: {
      ...twitterBase,
      title,
      description: info.description,
    },
  };
}

export default async function BlogCategoryPage({ params }: CategoryPageProps) {
  const { category } = await params;
  const info = BLOG_CATEGORIES_LIST.find((c) => c.slug === category);
  if (!info) notFound();

  let posts: BlogPost[] = BLOG_POSTS;
  try {
    const mongoPosts = await blogService.getPublishedPosts({ limit: 100 });
    if (mongoPosts && mongoPosts.length > 0) {
      posts = mongoPosts as unknown as BlogPost[];
    }
  } catch {}

  const collectionSchema = {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: `${info.title} Articles & Insights`,
    description: info.description,
    url: `${site.url}/blog/category/${info.slug}`,
  };

  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: site.url },
      { "@type": "ListItem", position: 2, name: "Blog", item: `${site.url}/blog` },
      { "@type": "ListItem", position: 3, name: info.name, item: `${site.url}/blog/category/${info.slug}` },
    ],
  };

  return (
    <>
      <JsonLd data={[collectionSchema, breadcrumbSchema]} />
      <BlogCategoryView categoryInfo={info} posts={posts} />
    </>
  );
}
