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

type EnquiryAction = "seller-enquiry" | "autoresponder-get" | "autoresponder-answers" | "autoresponder-details" | "autoresponder-refer";

// ─── Loop API V2: Marketing Enquiry Endpoints ──────────────────
// POST /marketing/enquiries/seller — submit seller enquiry
// GET /marketing/enquiries/auto-responder/{id}/{key} — read enquiry
// PUT .../auto-responder/{id}/answers/{key} — submit answers
// PUT .../auto-responder/{id}/details/{key} — update details
// PUT .../auto-responder/{id}/refer/{key} — refer enquiry
// Note: auto-responder uses personCode + key (UUID), not personId
// ────────────────────────────────────────────────────────────────
interface LoopBooleanResponse {
  success?: boolean;
  [key: string]: unknown;
}

interface LoopAutoResponderDetails {
  id?: number;
  questions?: unknown[];
  enquiryDetails?: unknown;
  [key: string]: unknown;
}

export async function marketingEnquiry(params: {
  accountId: string;
  teamName: string;
  action: EnquiryAction;
  // For seller-enquiry
  sellerEnquiryData?: Record<string, unknown>;
  // For autoresponder actions
  autoResponderId?: number;
  autoResponderKey?: string;
  // For autoresponder-answers
  answers?: unknown[];
  // For autoresponder-details
  details?: Record<string, unknown>;
}): Promise<string> {
  const { accountId, teamName, action } = params;

  if (action === "seller-enquiry") {
    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "marketing", "loop-marketing-enquiry",
      async (apiKey) => {
        return loopPost<LoopBooleanResponse>(
          apiKey, "/marketing/enquiries/seller",
          params.sellerEnquiryData ?? {}, "loop-marketing-enquiry", teamName
        );
      }
    );
    return `Seller enquiry submitted via team "${teamName}".`;
  }

  if (!params.autoResponderId || !params.autoResponderKey) {
    throw new Error("autoResponderId and autoResponderKey are required for autoresponder actions.");
  }
  const id = params.autoResponderId;
  const key = params.autoResponderKey;

  if (action === "autoresponder-get") {
    const result = await withTeamKey<LoopAutoResponderDetails>(
      accountId, teamName, "marketing", "loop-marketing-enquiry",
      async (apiKey) => {
        return loopGet<LoopAutoResponderDetails>(
          apiKey, `/marketing/enquiries/auto-responder/${id}/${key}`,
          "loop-marketing-enquiry", teamName
        );
      }
    );
    return JSON.stringify(result, null, 2);
  }

  if (action === "autoresponder-answers") {
    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "marketing", "loop-marketing-enquiry",
      async (apiKey) => {
        return loopPut<LoopBooleanResponse>(
          apiKey, `/marketing/enquiries/auto-responder/${id}/answers/${key}`,
          params.answers ?? [], "loop-marketing-enquiry", teamName
        );
      }
    );
    return `Auto-responder answers submitted for enquiry ${id} via team "${teamName}".`;
  }

  if (action === "autoresponder-details") {
    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "marketing", "loop-marketing-enquiry",
      async (apiKey) => {
        return loopPut<LoopBooleanResponse>(
          apiKey, `/marketing/enquiries/auto-responder/${id}/details/${key}`,
          params.details ?? {}, "loop-marketing-enquiry", teamName
        );
      }
    );
    return `Auto-responder details updated for enquiry ${id} via team "${teamName}".`;
  }

  if (action === "autoresponder-refer") {
    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "marketing", "loop-marketing-enquiry",
      async (apiKey) => {
        return loopPut<LoopBooleanResponse>(
          apiKey, `/marketing/enquiries/auto-responder/${id}/refer/${key}`,
          {}, "loop-marketing-enquiry", teamName
        );
      }
    );
    return `Enquiry ${id} referred via team "${teamName}".`;
  }

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