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

export interface TenantRecommendationFeed {
  recommended_products: Array<{ code: string; score?: number; reason?: string }>;
  recommended_bundles: Array<{ code: string; score?: number; reason?: string }>;
  recommended_services?: Array<{ code: string; score?: number; reason?: string }>;
  recommended_upgrades?: Array<{ code: string; score?: number; reason?: string }>;
  recommended_automation_packs?: Array<{ code: string; score?: number; reason?: string }>;
  recommended_extensions?: Array<{ code: string; score?: number; reason?: string }>;
  rule_trace?: string[];
}

const EMPTY: TenantRecommendationFeed = {
  recommended_products: [],
  recommended_bundles: [],
  recommended_services: [],
  recommended_upgrades: [],
  recommended_automation_packs: [],
  recommended_extensions: [],
};

/** Tenant recommendation feed — never invents suggestions. */
export async function loadTenantRecommendations(
  tenantId: string
): Promise<AdapterResult<TenantRecommendationFeed>> {
  const res = await commercialGet<TenantRecommendationFeed>(
    `/api/v1/commercial/recommendations/tenant?tenant_id=${encodeURIComponent(tenantId)}`
  );
  if (!res.ok) {
    return failResult(res.availability, res.message || "پیشنهادها در دسترس نیست", EMPTY);
  }
  const data = { ...EMPTY, ...res.data };
  const hasAny =
    data.recommended_products.length +
      data.recommended_bundles.length +
      (data.recommended_services?.length || 0) +
      (data.recommended_upgrades?.length || 0) +
      (data.recommended_automation_packs?.length || 0) +
      (data.recommended_extensions?.length || 0) >
    0;
  return {
    availability: hasAny ? "ready" : "empty",
    data,
    source: "commercial.recommendations.tenant",
    message: hasAny ? undefined : "پیشنهادی ثبت نشده",
  };
}
