import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { fetchQuery } from "convex/nextjs";
import { api } from "../../../../../../../convex/_generated/api";
import type { Id } from "../../../../../../../convex/_generated/dataModel";
import { isPetCategorySlug } from "@/lib/shop/constants";
import { SubCategoryPageContent } from "@/components/shop/SubCategoryPageContent";

type Props = {
  params: Promise<{ category: string; subCategory: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { category, subCategory } = await params;
  if (!isPetCategorySlug(category)) {
    return { title: "Not Found" };
  }
  const resolved = await fetchQuery(api.categories.getByPath, {
    categorySlug: category,
    subCategorySlug: subCategory,
  });
  if (!resolved) {
    return { title: "Not Found" };
  }
  const title = resolved.seoTitle ?? resolved.name;
  const description =
    resolved.seoDescription ?? resolved.description ?? `Shop ${resolved.name}`;
  return { title, description };
}

export default async function ShopSubCategoryPage({ params }: Props) {
  const { category, subCategory } = await params;

  if (!isPetCategorySlug(category)) {
    notFound();
  }

  const resolved = await fetchQuery(api.categories.getByPath, {
    categorySlug: category,
    subCategorySlug: subCategory,
  });

  if (!resolved) {
    notFound();
  }

  const subCategoryData = {
    _id: resolved._id as Id<"categories">,
    name: resolved.name,
    description: resolved.description,
    slug: resolved.slug,
    parentId: resolved.parentId as Id<"categories">,
  };

  return (
    <SubCategoryPageContent
      categorySlug={category}
      subCategorySlug={subCategory}
      subCategory={subCategoryData}
    />
  );
}
