/**
 * WHMCS Payments Provider - Mapper
 */

import type { PaymentMethod, PaymentGateway } from "../../contract";
import { paymentMethodSchema, paymentGatewaySchema } from "../../schema";
import {
  type WhmcsPaymentMethodRaw,
  type WhmcsPaymentGatewayRaw,
  whmcsPaymentMethodRawSchema,
  whmcsPaymentGatewayRawSchema,
} from "./raw.types";

const PAYMENT_TYPE_MAP: Record<string, PaymentMethod["type"]> = {
  creditcard: "CreditCard",
  bankaccount: "BankAccount",
  remotecard: "RemoteCreditCard",
  remotebankaccount: "RemoteBankAccount",
  manual: "Manual",
  remoteccreditcard: "RemoteCreditCard",
};

function mapPaymentMethodType(type: string): PaymentMethod["type"] {
  const normalized = type.trim().toLowerCase();
  return PAYMENT_TYPE_MAP[normalized] ?? "Manual";
}

const GATEWAY_TYPE_MAP: Record<string, PaymentGateway["type"]> = {
  merchant: "merchant",
  thirdparty: "thirdparty",
  tokenization: "tokenization",
  manual: "manual",
};

function mapGatewayType(type: string): PaymentGateway["type"] {
  const normalized = type.trim().toLowerCase();
  return GATEWAY_TYPE_MAP[normalized] ?? "manual";
}

function coerceBoolean(value: boolean | number | string | undefined): boolean {
  if (typeof value === "boolean") return value;
  if (typeof value === "number") return value === 1;
  if (typeof value === "string") return value === "1" || value.toLowerCase() === "true";
  return false;
}

export function transformWhmcsPaymentMethod(raw: unknown): PaymentMethod {
  const whmcs = whmcsPaymentMethodRawSchema.parse(raw);

  const paymentMethod: PaymentMethod = {
    id: whmcs.id,
    type: mapPaymentMethodType(whmcs.payment_type || whmcs.type || "manual"),
    description: whmcs.description,
    gatewayName: whmcs.gateway_name || whmcs.gateway,
    cardLastFour: whmcs.card_last_four,
    expiryDate: whmcs.expiry_date,
    cardType: whmcs.card_type,
    bankName: whmcs.bank_name,
    remoteToken: whmcs.remote_token,
    lastUpdated: whmcs.last_updated,
    isDefault: coerceBoolean(whmcs.is_default),
  };

  return paymentMethodSchema.parse(paymentMethod);
}

export function transformWhmcsPaymentGateway(raw: unknown): PaymentGateway {
  const whmcs = whmcsPaymentGatewayRawSchema.parse(raw);

  const gateway: PaymentGateway = {
    name: whmcs.name,
    displayName: whmcs.display_name || whmcs.name,
    type: mapGatewayType(whmcs.type),
    isActive: coerceBoolean(whmcs.visible),
    configuration: whmcs.configuration,
  };

  return paymentGatewaySchema.parse(gateway);
}

