import {
  aggregateAcrossTeams,
  formatAggregationResult,
  loopPut,
} from "../lib/loop-api.js";

// ─── Loop API V2: PUT /marketing/matching/other-matches ─────────
// Request body: array of property IDs
// Response: array of matching property summaries
// Schema not verified via curl (depends on matching state)
// ────────────────────────────────────────────────────────────────
interface LoopMatchingSummary {
  id?: number;
  address?: string;
  price?: number;
  type?: string;
  bedrooms?: number;
  [key: string]: unknown;
}

type Department = "sales" | "lettings";

export async function marketingMatchBatch(params: {
  accountId: string;
  propertyIds: number[];
  department: Department;
  teamName?: string;
}): Promise<string> {
  const { accountId, propertyIds, department, teamName } = params;

  const result = await aggregateAcrossTeams<LoopMatchingSummary>(
    accountId,
    "marketing",
    "loop-marketing-match-batch",
    async (apiKey, team) => {
      const prefix = department === "lettings" ? "/marketing/rentals" : "/marketing";
      const path = `${prefix}/matching/other-matches`;
      const data = await loopPut<LoopMatchingSummary[]>(apiKey, path, propertyIds, "loop-marketing-match-batch", team);
      return Array.isArray(data) ? data : [];
    },
    { teamName }
  );

  return formatAggregationResult(
    result,
    (p) => {
      const price = p.price ? ` — £${p.price.toLocaleString("en-GB")}` : "";
      const beds = p.bedrooms ? ` ${p.bedrooms}bed` : "";
      return `- ${p.address ?? "Unknown"}${price}${beds}`;
    },
    "matching properties"
  );
}
