import {
  type CollaboratorOfferResponse,
  isAcceptanceField,
  type LoanOffer,
  type LoanOfferPlanOption,
} from '../types';

import { collaboratorMinorUnitsToCurrency } from './collaboratorAmount';
import { resolvePeriodicity } from './periodicity';

function buildPlanOptionsFromMaxTerm(
  maxTerm: number,
): readonly LoanOfferPlanOption[] {
  const options: LoanOfferPlanOption[] = [];
  for (let weeks = 4; weeks <= maxTerm; weeks += 4) {
    options.push({ weeks, totalMultiplier: 1 });
  }
  return options;
}

export function mapCollaboratorOfferToLoanOffer(
  dto: CollaboratorOfferResponse,
): LoanOffer {
  let availability: LoanOffer['availability'] = 'no_offer';
  if (dto.status === 'OFFERED') {
    availability = 'available';
  } else if (dto.status === 'PENDING') {
    availability = 'paused';
  }

  const tnaAnnualPercent =
    dto.tna != null && Number.isFinite(dto.tna) ? dto.tna : undefined;

  return {
    id: dto.id,
    preApprovedMaxAmountMxn: collaboratorMinorUnitsToCurrency(dto.maxAmount),
    minAmountMxn: collaboratorMinorUnitsToCurrency(dto.minAmount),
    currency: dto.currency as 'MXN',
    availability,
    planOptions: buildPlanOptionsFromMaxTerm(dto.maxTerm),
    maxInstallmentAmountMxn: collaboratorMinorUnitsToCurrency(
      dto.maxInstallmentAmount,
    ),
    tnaAnnualPercent,
    tnaAnnualDecimal:
      tnaAnnualPercent != null ? tnaAnnualPercent / 100 : undefined,
    validUntil: dto.expiresAt,
    requiredAcceptanceFields: (dto.requiredAcceptanceFields ?? []).filter(
      isAcceptanceField,
    ),
    phoneNumber: dto.phoneNumber ?? undefined,
    periodicity: resolvePeriodicity(dto.periodicity),
  };
}
