"use client";

import { useQuery } from "@tanstack/react-query";
import { loadCommercialProducts } from "@/modules/commercial/adapters";

const PREFERRED_CODES = ["hospitality", "torbat_food", "torbat-food", "food", "torbatfood"];

/**
 * Resolve hospitality commercial product display name from Commercial Runtime.
 * Prefers exact product_code match; never hardcodes pricing/catalog rows.
 */
export function useHospitalityProductBrand() {
  return useQuery({
    queryKey: ["commercial", "hospitality-product-brand"],
    queryFn: async () => {
      const res = await loadCommercialProducts();
      const products = res.data || [];

      const exact = products.find((p) =>
        PREFERRED_CODES.includes((p.product_code || "").toLowerCase())
      );
      const byRoute = products.find((p) => p.default_route?.includes("/hospitality"));
      const byCategory = products.find(
        (p) =>
          p.category?.toLowerCase() === "hospitality" ||
          p.category?.toLowerCase() === "food"
      );
      const fuzzy = products.find((p) =>
        PREFERRED_CODES.some(
          (k) =>
            p.product_code?.toLowerCase() === k ||
            p.product_code?.toLowerCase().startsWith(`${k}.`)
        )
      );

      const match = exact || byRoute || byCategory || fuzzy;

      if (match) {
        return {
          displayName: match.display_name || match.product_code,
          productCode: match.product_code,
          availability: res.availability,
          message: res.message,
        };
      }
      return {
        displayName: null as string | null,
        productCode: null as string | null,
        availability: res.availability,
        message: res.message || "نام محصول از رجیستری تجاری بارگذاری نشد.",
      };
    },
    staleTime: 60_000,
  });
}
