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

type Department = "sales" | "lettings";

// ─── Loop API V2: POST /residential/{dept}/viewings ────────────
// Request body: { propertyId, date, time, attendeeName,
//   attendeeEmail?, attendeePhone? }
// Response: number (the created viewing ID) in data field
// ────────────────────────────────────────────────────────────────
interface LoopNumberResponse {
  result?: number;
  [key: string]: unknown;
}

export async function viewingCreate(params: {
  accountId: string;
  teamName: string;
  department: Department;
  propertyId: number;
  date: string;
  time: string;
  attendeeName: string;
  attendeeEmail?: string;
  attendeePhone?: string;
}): Promise<string> {
  const { accountId, teamName, department, ...body } = params;

  const result = await withTeamKey<LoopNumberResponse>(
    accountId,
    teamName,
    "viewings",
    "loop-viewing-create",
    async (apiKey) => {
      const path = `/residential/${department}/viewings`;
      return loopPost<LoopNumberResponse>(apiKey, path, body, "loop-viewing-create", teamName);
    }
  );

  const viewingId = result.result ?? "unknown";
  return `Viewing created (ID: ${viewingId}) for property ${params.propertyId} on ${params.date} at ${params.time} via team "${teamName}".`;
}
