import type { AdapterResult, CommercialProduct } from "../types";
import { commercialGet, extractItems, failResult, listResult } from "./http";

/**
 * Products from Core Commercial Registry only.
 * Launch routes come from product.default_route / href — NO FE hub path map.
 */
export async function loadCommercialProducts(): Promise<AdapterResult<CommercialProduct[]>> {
  const res = await commercialGet<unknown>("/api/v1/commercial/products");
  if (!res.ok) {
    return failResult(res.availability, res.message || "رجیستری محصول در دسترس نیست", []);
  }
  const items = extractItems<CommercialProduct>(res.data, ["items", "products"]);
  const normalized = items.map((p) => ({
    ...p,
    default_route: p.default_route || p.href || null,
    href: p.default_route || p.href || null,
  }));
  normalized.sort((a, b) => (a.display_order ?? 0) - (b.display_order ?? 0));
  return listResult(normalized, "commercial.products", "هیچ محصولی در رجیستری ثبت نشده است");
}
