import { callEndpoint } from "../api/client";
import { referralEndpoints } from "../api/referralEndpoints";

export type ReferralReason = "signup" | "transaction" | "event";

export interface ApplyReferralPayload {
  referralCode: string;
  uid: string;
  referralReason: ReferralReason;
  contextId: string;
}

export interface ApplyReferralResult {
  success: boolean;
  message?: string;
  error?: string;
}

export async function applyReferral(
  payload: ApplyReferralPayload
): Promise<ApplyReferralResult> {
  const trimmedCode = payload.referralCode.trim();

  if (!trimmedCode) {
    return { success: false, error: "Referral code is required" };
  }

  const body = {
    referralCode: trimmedCode,
    uid: payload.uid,
    referralReason: payload.referralReason,
    contextId: payload.contextId,
  };

  try {
    console.log("[ReferralService] Applying referral via API client", body);

    const res = await callEndpoint<any, typeof body>(referralEndpoints.apply, {
      body,
      headers: {
        "source-app": "amba-pay",
      },
    });

    const message =
      (res && (res.message || res.successMessage)) ||
      "Referral applied successfully";

    console.log("[ReferralService] Referral applied successfully", res);

    return { success: true, message };
  } catch (error) {
    console.error("[ReferralService] Error calling referral API", error);

    let parsedError: string | undefined;
    if (error instanceof Error) {
      try {
        const parsed = JSON.parse(error.message);
        if (parsed && typeof parsed.message === "string") {
          parsedError = parsed.message;
        }
      } catch {
        // ignore JSON parse failure, fall back to message
        parsedError = error.message;
      }
    }

    return {
      success: false,
      error: parsedError || "Failed to apply referral code",
    };
  }
}
