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

/** Generic metadata — never whitelist attribute keys. */
export async function loadCommercialMetadata(params: {
  target_kind: string;
  target_id?: string;
  target_code?: string;
}): Promise<AdapterResult<CommercialMetadataBag | null>> {
  const q = new URLSearchParams({ target_kind: params.target_kind });
  if (params.target_id) q.set("target_id", params.target_id);
  if (params.target_code) q.set("target_code", params.target_code);

  const res = await commercialGet<CommercialMetadataBag | { bag?: CommercialMetadataBag }>(
    `/api/v1/commercial/metadata?${q.toString()}`
  );
  if (!res.ok) {
    return failResult(res.availability, res.message || "metadata در دسترس نیست", null);
  }
  const bag =
    (res.data as { bag?: CommercialMetadataBag }).bag ||
    (res.data as CommercialMetadataBag);
  if (!bag || !bag.attributes) {
    return {
      availability: "empty",
      data: { attributes: {} },
      source: "commercial.metadata",
    };
  }
  return { availability: "ready", data: bag, source: "commercial.metadata" };
}
