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

// ─── Loop API V2: /marketing/matching/{id} ─────────────────────
// Returned HTTP 500 for test property 895155 — may require
// publishedToMatching: true. Exact response schema not verified.
// Fields below are from Swagger docs; [key: string]: unknown
// ensures any actual response fields are accessible.
// ────────────────────────────────────────────────────────────────
interface LoopMatchingProperty {
  id?: number;
  address?: string;
  price?: number;
  type?: string;
  bedrooms?: number;
  status?: string;
  description?: string;
  [key: string]: unknown;
}

interface LoopMatchingTeamProfile {
  name?: string;
  address?: string;
  phone?: string;
  email?: string;
  logoUrl?: string;
  [key: string]: unknown;
}

type Department = "sales" | "lettings";

export async function marketingMatchDetail(params: {
  accountId: string;
  propertyId: number;
  department: Department;
  includeTeamProfile?: boolean;
  teamName?: string;
}): Promise<string> {
  const { accountId, propertyId, department, includeTeamProfile = false, teamName } = params;

  const result = await aggregateAcrossTeams<LoopMatchingProperty>(
    accountId,
    "marketing",
    "loop-marketing-match",
    async (apiKey, team) => {
      const prefix = department === "lettings" ? "/marketing/rentals" : "/marketing";
      const path = `${prefix}/matching/${propertyId}`;
      const data = await loopGet<LoopMatchingProperty>(apiKey, path, "loop-marketing-match", team);
      if (data && typeof data === "object" && !Array.isArray(data)) {
        if (includeTeamProfile) {
          const profilePath = `${prefix}/matching/${propertyId}/team-profile`;
          const profile = await loopGet<LoopMatchingTeamProfile>(apiKey, profilePath, "loop-marketing-match", team).catch(() => null);
          if (profile) {
            (data as Record<string, unknown>)._teamProfile = profile;
          }
        }
        return [data];
      }
      return [];
    },
    { teamName }
  );

  return formatAggregationResult(
    result,
    (p) => {
      const lines = [`**${p.address ?? "Unknown address"}**`];
      if (p.price) lines.push(`Price: £${p.price.toLocaleString("en-GB")}`);
      if (p.type) lines.push(`Type: ${p.type}`);
      if (p.bedrooms) lines.push(`Bedrooms: ${p.bedrooms}`);
      if (p.status) lines.push(`Status: ${p.status}`);
      if (p.description) lines.push(`\n${p.description}`);
      const profile = (p as Record<string, unknown>)._teamProfile as LoopMatchingTeamProfile | undefined;
      if (profile) {
        lines.push(`\n**Team:** ${profile.name ?? ""} — ${profile.address ?? ""} | ${profile.phone ?? ""} | ${profile.email ?? ""}`);
      }
      return lines.join("\n");
    },
    "matching property details"
  );
}
