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

type Department = "sales" | "lettings";

// ─── Loop API V2: /feedback/residential/{dept}/viewings/{id} ───
// Returns null when no feedback has been submitted. Exact schema
// not verified — endpoint returned null for all test viewings.
// Fields below are the documented schema; the [key: string]: unknown
// catch-all ensures any actual response fields are accessible.
// ────────────────────────────────────────────────────────────────
interface LoopViewingFeedback {
  viewingId?: number;
  propertyAddress?: string;
  date?: string;
  attendeeName?: string;
  feedback?: string;
  rating?: number;
  status?: string;
  [key: string]: unknown;
}

interface LoopBooleanResponse {
  success?: boolean;
  [key: string]: unknown;
}

export async function feedbackGet(params: {
  accountId: string;
  teamName: string;
  viewingId: number;
  department: Department;
}): Promise<string> {
  const { accountId, teamName, viewingId, department } = params;

  const result = await withTeamKey<LoopViewingFeedback>(
    accountId,
    teamName,
    "feedback",
    "loop-feedback-get",
    async (apiKey) => {
      const path = `/feedback/residential/${department}/viewings/${viewingId}`;
      return loopGet<LoopViewingFeedback>(apiKey, path, "loop-feedback-get", teamName);
    }
  );

  if (!result || (Array.isArray(result) && result.length === 0)) {
    return `No feedback found for viewing ${viewingId} (${department}) via team "${teamName}".`;
  }

  const f = result;
  const lines = [`**Feedback for viewing ${viewingId}**`];
  if (f.propertyAddress) lines.push(`Property: ${f.propertyAddress}`);
  if (f.date) lines.push(`Date: ${f.date}`);
  if (f.attendeeName) lines.push(`Attendee: ${f.attendeeName}`);
  if (f.rating != null) lines.push(`Rating: ★${f.rating}`);
  if (f.status) lines.push(`Status: ${f.status}`);
  if (f.feedback) lines.push(`Feedback: ${f.feedback}`);
  return lines.join("\n");
}

export async function feedbackSubmit(params: {
  accountId: string;
  teamName: string;
  viewingId: number;
  department: Department;
  feedback: string;
}): Promise<string> {
  const { accountId, teamName, viewingId, department, feedback } = params;

  await withTeamKey<LoopBooleanResponse>(
    accountId,
    teamName,
    "feedback",
    "loop-feedback-submit",
    async (apiKey) => {
      const path = `/feedback/residential/${department}/viewings/${viewingId}/feedback`;
      return loopPost<LoopBooleanResponse>(apiKey, path, { result: feedback }, "loop-feedback-submit", teamName);
    }
  );

  return `Feedback submitted for viewing ${viewingId} (${department}) via team "${teamName}".`;
}
