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

type SupplierAction =
  | "maintenance-jobs"
  | "maintenance-complete"
  | "maintenance-quotes"
  | "maintenance-submit-quote"
  | "board-jobs"
  | "board-complete";

// ─── Loop API V2: Supplier Endpoints ───────────────────────────
// /supplier/maintenance/{code}/{jobId}/job-list — GET job list
// /supplier/maintenance/{code}/{jobId}/complete — POST complete
// /supplier/maintenance/{code}/{jobId}/quote-list — GET quotes
// /supplier/maintenance/{code}/{quoteId}/quote-for-job — PUT quote
// /supplier/board-contractor/{code}/{jobId}/job-list — GET jobs
// /supplier/board-contractor/{code}/{jobId}/complete — POST complete
// Uses quoteCode/code (string) and jobId (int64)
// ────────────────────────────────────────────────────────────────
interface LoopSupplierResult {
  [key: string]: unknown;
}

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

export async function supplier(params: {
  accountId: string;
  teamName: string;
  action: SupplierAction;
  code: string;
  jobId?: number;
  // For maintenance-submit-quote
  quoteId?: number;
  quoteData?: Record<string, unknown>;
  // For board-complete
  completionData?: Record<string, unknown>;
}): Promise<string> {
  const { accountId, teamName, action, code } = params;

  // jobId is required for all actions except maintenance-submit-quote
  const jobId = params.jobId;
  if (action !== "maintenance-submit-quote" && jobId == null) {
    throw new Error(`jobId is required for action "${action}".`);
  }

  if (action === "maintenance-jobs") {
    const result = await withTeamKey<LoopSupplierResult>(
      accountId, teamName, "supplier", "loop-supplier",
      async (apiKey) => {
        return loopGet<LoopSupplierResult>(
          apiKey, `/supplier/maintenance/${encodeURIComponent(code)}/${jobId}/job-list`,
          "loop-supplier", teamName
        );
      }
    );
    return JSON.stringify(result, null, 2);
  }

  if (action === "maintenance-complete") {
    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "supplier", "loop-supplier",
      async (apiKey) => {
        return loopPost<LoopBooleanResponse>(
          apiKey, `/supplier/maintenance/${encodeURIComponent(code)}/${jobId}/complete`,
          {}, "loop-supplier", teamName
        );
      }
    );
    return `Maintenance job ${jobId} marked complete via team "${teamName}".`;
  }

  if (action === "maintenance-quotes") {
    const result = await withTeamKey<LoopSupplierResult>(
      accountId, teamName, "supplier", "loop-supplier",
      async (apiKey) => {
        return loopGet<LoopSupplierResult>(
          apiKey, `/supplier/maintenance/${encodeURIComponent(code)}/${jobId}/quote-list`,
          "loop-supplier", teamName
        );
      }
    );
    return JSON.stringify(result, null, 2);
  }

  if (action === "maintenance-submit-quote") {
    if (!params.quoteId) throw new Error("quoteId is required for maintenance-submit-quote.");
    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "supplier", "loop-supplier",
      async (apiKey) => {
        return loopPut<LoopBooleanResponse>(
          apiKey, `/supplier/maintenance/${encodeURIComponent(code)}/${params.quoteId}/quote-for-job`,
          params.quoteData ?? {}, "loop-supplier", teamName
        );
      }
    );
    return `Quote ${params.quoteId} submitted via team "${teamName}".`;
  }

  if (action === "board-jobs") {
    const result = await withTeamKey<LoopSupplierResult>(
      accountId, teamName, "supplier", "loop-supplier",
      async (apiKey) => {
        return loopGet<LoopSupplierResult>(
          apiKey, `/supplier/board-contractor/${encodeURIComponent(code)}/${jobId}/job-list`,
          "loop-supplier", teamName
        );
      }
    );
    return JSON.stringify(result, null, 2);
  }

  if (action === "board-complete") {
    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "supplier", "loop-supplier",
      async (apiKey) => {
        return loopPost<LoopBooleanResponse>(
          apiKey, `/supplier/board-contractor/${encodeURIComponent(code)}/${jobId}/complete`,
          params.completionData ?? {}, "loop-supplier", teamName
        );
      }
    );
    return `Board contractor job ${jobId} marked complete via team "${teamName}".`;
  }

  throw new Error(`Unknown supplier action: ${action}`);
}
