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

type Department = "sales" | "lettings";

// Feedback parties map to swagger endpoints:
// sales: buyer-feedback, seller-feedback
// lettings: renter-feedback, landlord-feedback
type FeedbackParty = "buyer" | "seller" | "renter" | "landlord";
type Action = "note" | "feedback";

// ─── Loop API V2: POST /residential/{dept}/viewings/{id}/{suffix}
// Suffix: "note" for notes, "{party}-feedback" for feedback
// Request body: { result: string } (StringResponse format)
// Response: boolean success
// ────────────────────────────────────────────────────────────────
interface LoopBooleanResponse {
  success?: boolean;
  [key: string]: unknown;
}

export async function viewingUpdate(params: {
  accountId: string;
  teamName: string;
  viewingId: number;
  department: Department;
  action: Action;
  text: string;
  feedbackParty?: FeedbackParty;
}): Promise<string> {
  const { accountId, teamName, viewingId, department, action, text, feedbackParty } = params;

  if (action === "feedback" && !feedbackParty) {
    throw new Error("feedbackParty is required when action is 'feedback'. Use: buyer, seller, renter, or landlord.");
  }

  await withTeamKey<LoopBooleanResponse>(
    accountId,
    teamName,
    "viewings",
    "loop-viewing-update",
    async (apiKey) => {
      const suffix = action === "note"
        ? "note"
        : `${feedbackParty}-feedback`;
      const path = `/residential/${department}/viewings/${viewingId}/${suffix}`;
      // Loop expects the text as a StringResponse body
      return loopPost<LoopBooleanResponse>(apiKey, path, { result: text }, "loop-viewing-update", teamName);
    }
  );

  const actionLabel = action === "note" ? "Note added" : `${feedbackParty} feedback recorded`;
  return `${actionLabel} for viewing ${viewingId} (${department}) via team "${teamName}".`;
}
