import { loopPost, withTeamKey } from "../lib/loop-api.js";

type Department = "sales" | "lettings";
type MatchAction = "viewing" | "information" | "callback";

// ─── Loop API V2: POST /marketing/matching/{id}/{action} ────────
// Actions: viewing, information, callback
// Request body: { name?, email?, phone?, message? }
// Response: boolean success
// ────────────────────────────────────────────────────────────────
interface LoopBooleanResponse {
  success?: boolean;
  [key: string]: unknown;
}

export async function marketingMatchRequest(params: {
  accountId: string;
  teamName: string;
  propertyId: number;
  department: Department;
  action: MatchAction;
  name?: string;
  email?: string;
  phone?: string;
  message?: string;
}): Promise<string> {
  const { accountId, teamName, propertyId, department, action, ...body } = params;

  await withTeamKey<LoopBooleanResponse>(
    accountId,
    teamName,
    "marketing",
    "loop-marketing-match-request",
    async (apiKey) => {
      const prefix = department === "lettings" ? "/marketing/rentals" : "/marketing";
      const path = `${prefix}/matching/${propertyId}/${action}`;
      return loopPost<LoopBooleanResponse>(apiKey, path, body, "loop-marketing-match-request", teamName);
    }
  );

  return `${action} request submitted for matching property ${propertyId} (${department}) via team "${teamName}".`;
}
