import type { Metadata } from "next";

import StoresCommonClient from "@/components/common/StoresCommonClient";
import { getStoresServer } from "@/services/store.service.server";
import { POPULAR_CATEGORIES } from "@/utils/constants";
import "../../../styles/deal-style.css";

export const revalidate = 3600; // Revalidate every hour

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

// Module-level cache for category coupon data
const cachedCategoryData: { [key: string]: any } = {};

// Generate metadata for SEO
export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const resolvedParams = await params;
  const categoryId = resolvedParams.slug || "all";
  const decodedCategory = decodeURIComponent(categoryId);
  const alphabet = "all";
  const cacheKey = `${categoryId}-${alphabet}`; // Use raw categoryId for cache key

  // Fetch data (will be cached for page render)
  if (!cachedCategoryData[cacheKey]) {
    const storesData = await getStoresServer(decodedCategory, alphabet);
    cachedCategoryData[cacheKey] = {
      storesData,
    };
  }

  const { storesData } = cachedCategoryData[cacheKey];
  const pageHeading = storesData?.page_heading || decodedCategory;
  const storesCount = storesData?.stores?.length || 0;

  return {
    title: `${pageHeading} Coupons & Deals | Rebates.com`,
    description: `Find ${storesCount} stores offering ${decodedCategory} coupons and cashback deals. Save money with exclusive discounts and promo codes.`,
    keywords: `${decodedCategory}, coupons, deals, promo codes, cashback, discounts`,
    openGraph: {
      title: `${pageHeading} Coupons & Deals`,
      description: `Find ${storesCount} stores offering ${decodedCategory} coupons and cashback deals.`,
      type: "website",
    },
  };
}

export default async function CategoryCouponsPage({ params }: Props) {
  const resolvedParams = await params;
  const categoryId = resolvedParams.slug || "all";
  const decodedCategory = decodeURIComponent(categoryId);
  const alphabet = "all";
  const cacheKey = `${categoryId}-${alphabet}`;

  // Use cached data from generateMetadata or fetch if not available
  if (!cachedCategoryData[cacheKey]) {
    const storesData = await getStoresServer(decodedCategory, alphabet);
    cachedCategoryData[cacheKey] = {
      storesData,
    };
  }

  const { storesData } = cachedCategoryData[cacheKey];

  return (
    <StoresCommonClient
      routeType="category"
      alphabet={alphabet}
      categoryId={decodedCategory}
      categoriesData={POPULAR_CATEGORIES}
      storesData={storesData}
    />
  );
}
