import { type CollaboratorPaymentItem } from '../types';

function coerceFiniteNumber(value: unknown): number | undefined {
  if (typeof value === 'number' && Number.isFinite(value)) {
    return value;
  }
  if (typeof value === 'string' && value.trim() !== '') {
    const n = Number(value);
    return Number.isFinite(n) ? n : undefined;
  }
  return undefined;
}

function coerceNonEmptyString(value: unknown): string | undefined {
  return typeof value === 'string' && value.trim() !== ''
    ? value.trim()
    : undefined;
}

function normalizePaymentItem(raw: unknown): CollaboratorPaymentItem | null {
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
    return null;
  }
  const o = raw as Record<string, unknown>;
  const installmentNumber =
    coerceFiniteNumber(o.installmentNumber) ??
    coerceFiniteNumber(o.installment_number) ??
    coerceFiniteNumber(o.paymentNumber) ??
    coerceFiniteNumber(o.payment_number);
  const sequence = coerceFiniteNumber(o.sequence);

  return {
    installmentNumber,
    sequence,
    dueDate:
      coerceNonEmptyString(o.dueDate) ?? coerceNonEmptyString(o.due_date),
    amount: coerceFiniteNumber(o.amount),
    dueAmount:
      coerceFiniteNumber(o.dueAmount) ?? coerceFiniteNumber(o.due_amount),
    status: coerceNonEmptyString(o.status),
  };
}

function mapPaymentsArray(items: unknown[]): CollaboratorPaymentItem[] {
  return items
    .map(normalizePaymentItem)
    .filter((x): x is CollaboratorPaymentItem => x != null);
}

export function normalizeCollaboratorPaymentsResponse(
  data: unknown,
): CollaboratorPaymentItem[] {
  if (Array.isArray(data)) {
    return mapPaymentsArray(data);
  }
  if (data && typeof data === 'object') {
    const bag = data as Record<string, unknown>;
    if (Array.isArray(bag.data)) {
      return mapPaymentsArray(bag.data);
    }
    if (Array.isArray(bag.payments)) {
      return mapPaymentsArray(bag.payments);
    }
    if (Array.isArray(bag.items)) {
      return mapPaymentsArray(bag.items);
    }
  }
  return [];
}
