import type { ProductCardProps } from "@/components/product/ProductCard";
import { formatPrice } from "@repo/utils";

/**
 * Enriched product shape returned by Convex products.listActive (and similar).
 * Product + images[] + variants[] from model/products enrichProducts.
 * Category slugs are on the product; use them as the single source of truth for product URLs.
 */
export type EnrichedProduct = {
  _id: string;
  name: string;
  slug: string;
  parentCategorySlug: string;
  childCategorySlug: string;
  brand?: string;
  averageRating?: number;
  reviewCount?: number;
  createdAt?: number;
  images: { url: string; alt?: string; position: number }[];
  variants: { price: number; compareAtPrice?: number; name?: string }[];
};

/** Build product URL from product slugs only. Single source of truth: /shop/{parent}/{child}/{slug}. */
export function getProductUrl(product: {
  parentCategorySlug: string;
  childCategorySlug: string;
  slug: string;
}): string {
  return `/shop/${product.parentCategorySlug}/${product.childCategorySlug}/${product.slug}`;
}

/**
 * Map Convex enriched product to ProductCardProps.
 * Product URL is always built from the product object: /shop/{parentCategorySlug}/{childCategorySlug}/{slug}.
 */
export function enrichedProductToCardProps(product: EnrichedProduct): ProductCardProps {
  const firstImage = product.images[0];
  const firstVariant = product.variants[0];
  const priceCents = firstVariant?.price ?? 0;
  const compareAtCents = firstVariant?.compareAtPrice;
  const hasSale = compareAtCents != null && compareAtCents > priceCents;

  const url = getProductUrl(product);

  return {
    brand: product.brand ?? "Brand",
    name: product.name,
    price: formatPrice(priceCents),
    compareAtPrice: compareAtCents != null ? formatPrice(compareAtCents) : undefined,
    imageSrc: firstImage?.url ?? "/images/placeholder-product.png",
    imageAlt: firstImage?.alt ?? product.name,
    url,
    rating: product.averageRating ?? 0,
    reviewCount: product.reviewCount ?? 0,
    badge: hasSale ? "sale" : undefined,
    productId: product._id,
  };
}
