/** صفحه دسته‌بندی: /c/مراقبت-پوست/سرم */
import type { Metadata } from "next";
import { seo } from "@/lib/seo";
import { notFound } from "next/navigation";
import { ListingView } from "@/components/listing/ListingView";
import { Breadcrumbs } from "@/components/ui/Breadcrumbs";
import { parseListingParams, listingSeo } from "@/lib/listing-params";
import { decodeSegment } from "@/lib/route-params";
import { getCategoryIndex, listProducts } from "@/server/services/catalog";

type Props = {
  params: Promise<{ slug: string[] }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

/** دسته را پیدا می‌کند و مطمئن می‌شود مسیر کامل آدرس درست است */
async function resolveCategory(segments: string[]) {
  const slugs = segments.map(decodeSegment);
  const cats = await getCategoryIndex();
  const category = cats.all.find((c) => c.slug === slugs[slugs.length - 1]);
  if (!category || cats.href(category.id) !== `/c/${slugs.join("/")}`) return undefined;
  return { category, cats };
}

export async function generateMetadata({ params, searchParams }: Props): Promise<Metadata> {
  const found = await resolveCategory((await params).slug);
  if (!found) return {};
  const { category, cats } = found;
  const { path, titleSuffix } = listingSeo(cats.href(category.id), parseListingParams(await searchParams, { categoryId: category.id }));
  return seo({
    title: `خرید ${category.name}${titleSuffix}`,
    description: category.description ?? `خرید آنلاین ${category.name} اصل با ضمانت اصالت و ارسال سریع از زهورا.`,
    path,
  });
}

export default async function CategoryPage({ params, searchParams }: Props) {
  const found = await resolveCategory((await params).slug);
  if (!found) notFound();
  const { category, cats } = found;

  const basePath = cats.href(category.id);
  const filters = parseListingParams(await searchParams, { categoryId: category.id });
  const result = await listProducts(filters);
  const path = cats.path(category.id);
  const tree = cats.tree;

  // زیردسته‌ها: اگر دسته اصلی است فرزندانش، وگرنه هم‌سطح‌هایش
  const root = tree.find((r) => r.id === (category.parentId ?? category.id))!;
  const subcategories = [
    { name: `همه ${root.name}`, href: cats.href(root.id), active: root.id === category.id },
    ...root.children.map((c) => ({ name: c.name, href: cats.href(c.id), active: c.id === category.id })),
  ];

  return (
    <ListingView
      title={category.name}
      description={category.description}
      breadcrumbs={<Breadcrumbs items={path.map((c) => ({ name: c.name, href: cats.href(c.id) }))} />}
      basePath={basePath}
      filters={filters}
      result={result}
      subcategories={root.children.length ? subcategories : []}
    />
  );
}
