/**
 * ============================================
 * CATCH-ALL SEO URL ROUTE
 * ============================================
 * Resolves slug paths to the correct page.
 *
 * Examples:
 *   /Variant-product/SWDEMO10005.1  → product detail page
 *   /Food                           → category listing page
 *   /Clothing/Men/                  → nested category listing page
 *
 * Resolution order:
 *   1. Try Shopware /seo-url (works for non-headless sales channels)
 *   2. Headless fallback: last segment looks like a productNumber → PDP
 *   3. Headless fallback: walk navigation tree, match each segment to a
 *      category translated-name slug
 *
 * The page component is rendered inline so the browser keeps the slug URL
 * in the address bar — no internal redirect to /products/[id] or
 * /category/[id]. The `_fromSeo` flag tells those routes to skip their
 * own force-redirect (otherwise we'd bounce back and forth).
 */

import {
  resolveSeoUrl,
  getProductByNumber,
  resolveCategoryByPath,
} from '@/lib/shopware-api';
import { notFound } from 'next/navigation';
import ProductDetailPage from '@/app/products/[id]/page';
import CategoryPage from '@/app/category/[id]/page';

interface PageProps {
  params: Promise<{ slug: string[] }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}

async function resolvePath(
  segments: string[]
): Promise<{ routeName: string; foreignKey: string } | null> {
  const cleaned = segments.filter(Boolean);
  if (cleaned.length === 0) return null;

  const seoPath = cleaned.join('/');
  const altPath = seoPath.endsWith('/') ? seoPath.slice(0, -1) : `${seoPath}/`;

  const fromSeo =
    (await resolveSeoUrl(seoPath)) || (await resolveSeoUrl(altPath));
  if (fromSeo) return fromSeo;

  // Headless fallback: try the last segment as a product number
  // (URLs are /{slug(name)}/{productNumber}, so this only kicks in when
  //  the path has ≥2 segments).
  if (cleaned.length >= 2) {
    const productNumber = decodeURIComponent(cleaned[cleaned.length - 1]);
    const product = await getProductByNumber(productNumber);
    if (product) {
      return { routeName: 'frontend.detail.page', foreignKey: product.id };
    }
  }

  // Headless fallback: walk navigation tree by slugified category names
  const category = await resolveCategoryByPath(cleaned);
  if (category) {
    return { routeName: 'frontend.navigation.page', foreignKey: category.id };
  }

  return null;
}

export default async function SeoUrlPage({ params, searchParams }: PageProps) {
  const { slug } = await params;
  const sp = await searchParams;

  const match = await resolvePath(slug);
  if (!match) {
    notFound();
  }

  switch (match.routeName) {
    case 'frontend.detail.page':
      return (
        <ProductDetailPage
          params={Promise.resolve({ id: match.foreignKey })}
          searchParams={Promise.resolve({ ...sp, _fromSeo: '1' }) as any}
        />
      );

    case 'frontend.navigation.page':
    case 'frontend.landing.page':
      return (
        <CategoryPage
          params={Promise.resolve({ id: match.foreignKey })}
          searchParams={Promise.resolve({ ...sp, _fromSeo: '1' }) as any}
        />
      );

    default:
      notFound();
  }
}
