import api from 'src/config/api';

import { type FinishedLoan } from '../types';
import { collaboratorMinorUnitsToCurrency } from '../utils/collaboratorAmount';
import { resolvePeriodicity } from '../utils/periodicity';

type CollaboratorPlanHistoryItem = {
  id: string;
  loanOfferId: string;
  instanceId: number;
  installmentsChosen: number;
  totalAmount: number;
  amountPerCycle: number;
  totalToRepay: number;
  startDate: string | null;
  endDate: string | null;
  completedAt: string | null;
  status?: string;
  periodicity?: string | null;
};

type CollaboratorPlanHistoryResponse = {
  data: CollaboratorPlanHistoryItem[];
  pagination: {
    page: number;
    size: number;
    totalElements: number;
    totalPages: number;
    hasMore: boolean;
  };
};

const HISTORY_PAGE_SIZE = 100;
const HISTORY_MAX_PAGES = 50;

function mapHistoryItem(item: CollaboratorPlanHistoryItem): FinishedLoan {
  return {
    id: item.id,
    amount: collaboratorMinorUnitsToCurrency(item.totalAmount),
    weeks: item.installmentsChosen,
    closeDate: item.completedAt ?? item.endDate ?? '',
    status: item.status === 'CANCELLED' ? 'CANCELLED' : 'PAID',
    periodicity: resolvePeriodicity(item.periodicity),
  };
}

export async function fetchCollaboratorFinishedLoans(): Promise<
  FinishedLoan[]
> {
  const items: CollaboratorPlanHistoryItem[] = [];
  let page = 0;
  let hasMore = true;

  while (hasMore && page < HISTORY_MAX_PAGES) {
    const { data } = await api.get<CollaboratorPlanHistoryResponse>(
      '/microloans/collaborator/plans/history',
      { params: { page, size: HISTORY_PAGE_SIZE } },
    );
    items.push(...data.data);
    hasMore = data.pagination.hasMore;
    page += 1;
  }

  return items.map(mapHistoryItem);
}
