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

// ─── Loop API V2: /property/residential/{dept}/listed/{channel} ─
// Returns full property detail enriched with listing metadata:
//   listingId, propertyId, propertyRefId, channel, displayAddress,
//   propertyAddress, address_* fields, status, propertyType,
//   dateLaunched, price, bedrooms, bathrooms, receptionRooms,
//   shortDescription, features[], images[]
// ─────────────────────────────────────────────────────────────────
interface LoopPropertyListing {
  listingId?: number;
  propertyId?: number;
  propertyRefId?: string;
  channel?: string;
  propertyAddress?: string;
  displayAddress?: string;
  status?: string;
  propertyType?: string;
  dateLaunched?: string;
  price?: number;
  priceQualifier?: string;
  bedrooms?: number;
  bathrooms?: number;
  receptionRooms?: number;
  shortDescription?: string;
  features?: string[];
  images?: { url: string }[];
  [key: string]: unknown;
}

type Department = "sales" | "lettings" | "both";
type Channel = "rightmove" | "onTheMarket" | "zoopla" | "website";

export async function propertyListed(params: {
  accountId: string;
  channel: Channel;
  department?: Department;
  includeSold?: boolean;
  teamName?: string;
  limit?: number;
}): Promise<string> {
  const { accountId, channel, department = "both", includeSold = false, teamName, limit } = params;

  const result = await aggregateAcrossTeams<LoopPropertyListing>(
    accountId,
    "properties",
    "loop-property-listed",
    async (apiKey, team) => {
      const all: LoopPropertyListing[] = [];
      const depts: string[] =
        department === "both" ? ["sales", "lettings"] : [department];

      for (const dept of depts) {
        const path = `/property/residential/${dept}/listed/${channel}`;
        const data = await loopGet<LoopPropertyListing[]>(apiKey, path, "loop-property-listed", team);
        if (Array.isArray(data)) all.push(...data);
      }

      if (includeSold) {
        const soldPath = `/property/residential/sold/${channel}`;
        const soldData = await loopGet<LoopPropertyListing[]>(apiKey, soldPath, "loop-property-listed", team);
        if (Array.isArray(soldData)) all.push(...soldData);
      }

      return all;
    },
    { teamName, limitPerTeam: limit ?? 50, limitTotal: limit ?? 200 }
  );

  return formatAggregationResult(
    result,
    (p) => {
      const addr = p.displayAddress ?? p.propertyAddress ?? "Unknown address";
      const id = p.propertyId != null ? ` [ID: ${p.propertyId}]` : "";
      const price = p.price ? ` — £${p.price.toLocaleString("en-GB")}` : "";
      const beds = p.bedrooms ? ` ${p.bedrooms}bed` : "";
      const propType = p.propertyType ? ` (${p.propertyType})` : "";
      const status = p.status ? ` [${p.status}]` : "";
      const photos = p.images?.length ? ` ${p.images.length} photo${p.images.length !== 1 ? "s" : ""}` : "";
      return `- ${addr}${id}${price}${beds}${propType}${status}${photos}`;
    },
    `${channel} listings`
  );
}
