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

type PreferencesAction = "read" | "write";

// ─── Loop API V2: /customer/preferences/{personCode} ───────────
// Uses personCode (encoded), NOT raw personId from /people.
// personCode is obtained from marketing context (auto-responder,
// matching), not from standard /people endpoints.
// GET returns preferences object; POST updates it.
// ────────────────────────────────────────────────────────────────
interface LoopCustomerPreferences {
  personCode?: number;
  preferences?: Record<string, unknown>;
  [key: string]: unknown;
}

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

export async function customerPreferences(params: {
  accountId: string;
  teamName: string;
  personCode: number;
  action: PreferencesAction;
  preferences?: Record<string, unknown>;
}): Promise<string> {
  const { accountId, teamName, personCode, action } = params;

  if (action === "read") {
    const result = await withTeamKey<LoopCustomerPreferences>(
      accountId, teamName, "customer", "loop-customer-preferences",
      async (apiKey) => {
        return loopGet<LoopCustomerPreferences>(
          apiKey, `/customer/preferences/${personCode}`,
          "loop-customer-preferences", teamName
        );
      }
    );

    if (!result || (Array.isArray(result) && result.length === 0)) {
      return `No preferences found for person ${personCode} via team "${teamName}".`;
    }
    return JSON.stringify(result, null, 2);
  }

  if (action === "write") {
    if (!params.preferences) {
      throw new Error("preferences object is required when action is 'write'.");
    }

    await withTeamKey<LoopBooleanResponse>(
      accountId, teamName, "customer", "loop-customer-preferences",
      async (apiKey) => {
        return loopPost<LoopBooleanResponse>(
          apiKey, `/customer/preferences/${personCode}`,
          params.preferences!, "loop-customer-preferences", teamName
        );
      }
    );
    return `Preferences updated for person ${personCode} via team "${teamName}".`;
  }

  throw new Error(`Unknown action: ${action}. Use "read" or "write".`);
}
