import { getProductCategories } from "@/lib/api/categories";
import { getPublishedProducts } from "@/lib/api/products";
import { getStoreItems } from "@/lib/api/store-items";
import type { ApiProduct, ApiStoreItem } from "@/lib/api/types";
import type { MenuSection, Product } from "@/data/products";

const PLACEHOLDER = "/product-placeholder.svg";
const DEFAULT_DESCRIPTION =
  "تازه‌آماده‌شده در اک؛ ترکیبی از طعم اصیل و کیفیت روزانه.";

function pickPreferredVariant(
  current: ApiStoreItem,
  candidate: ApiStoreItem,
): ApiStoreItem {
  if (candidate.discountedPrice != null && current.discountedPrice == null) {
    return candidate;
  }

  if (
    candidate.discountedPrice != null &&
    current.discountedPrice != null &&
    candidate.discountedPrice < current.discountedPrice
  ) {
    return candidate;
  }

  if (candidate.price != null && current.price == null) {
    return candidate;
  }

  if (candidate.productImage && !current.productImage) {
    return candidate;
  }

  if (candidate.isFestival && !current.isFestival) {
    return candidate;
  }

  return current;
}

function dedupeStoreItemsByProduct(items: ApiStoreItem[]): ApiStoreItem[] {
  const byProduct = new Map<string, ApiStoreItem>();

  for (const item of items) {
    const existing = byProduct.get(item.productId);
    byProduct.set(
      item.productId,
      existing ? pickPreferredVariant(existing, item) : item,
    );
  }

  return [...byProduct.values()];
}

function stripHtml(html: string | null | undefined): string {
  if (!html) return "";
  return html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
}

function resolvePrice(item: ApiStoreItem): number | null {
  if (item.discountedPrice != null) return item.discountedPrice;
  if (item.price != null) return item.price;
  return null;
}

function resolveImages(
  item: ApiStoreItem,
  product: ApiProduct | undefined,
): string[] {
  const images: string[] = [];

  if (item.productImage) images.push(item.productImage);
  if (product?.thumbnailUrl) images.push(product.thumbnailUrl);
  if (product?.image) images.push(product.image);
  for (const image of product?.images ?? []) {
    if (image) images.push(image);
  }

  const unique = [...new Set(images.filter(Boolean))];
  return unique.length > 0 ? unique : [PLACEHOLDER];
}

function toProduct(
  item: ApiStoreItem,
  product: ApiProduct | undefined,
  categorySlug: string,
): Product {
  const description =
    product?.summary?.trim() ||
    stripHtml(product?.descriptionHtml) ||
    DEFAULT_DESCRIPTION;

  return {
    id: item.productId,
    name: item.productNameFa || item.productTitle,
    nameEn: item.productTitle || product?.title || "",
    price: resolvePrice(item),
    category: categorySlug,
    images: resolveImages(item, product),
    description,
  };
}

export async function getMenuSections(): Promise<MenuSection[]> {
  const [categories, storeItems, products] = await Promise.all([
    getProductCategories(),
    getStoreItems(),
    getPublishedProducts(),
  ]);

  const productsById = new Map(products.map((product) => [product.id, product]));
  const categoryById = new Map(categories.map((category) => [category.id, category]));

  const mapped = dedupeStoreItemsByProduct(storeItems)
    .map((item) => {
      const product = productsById.get(item.productId);
      const categoryId = product?.categoryId;
      const category = categoryId ? categoryById.get(categoryId) : undefined;
      if (!category) return null;
      return toProduct(item, product, category.slug);
    })
    .filter((product): product is Product => product !== null);

  return categories
    .map((category) => ({
      id: category.slug,
      label: category.nameFa || category.name,
      products: mapped.filter((product) => product.category === category.slug),
    }))
    .filter((section) => section.products.length > 0);
}
