import api from 'src/config/api';

import {
  type AcceptOfferRequest,
  type AcceptOfferResponse,
  type CollaboratorLoanPlanResponse,
  type CollaboratorOfferResponse,
  type CollaboratorStatusResponse,
  type SimulateRequest,
  type SimulateResponse,
} from '../types';

export async function fetchCollaboratorStatus(): Promise<CollaboratorStatusResponse> {
  const { data } = await api.get<CollaboratorStatusResponse>(
    '/microloans/collaborator/status',
  );
  return data;
}

export async function fetchActiveCollaboratorOffer(): Promise<CollaboratorOfferResponse> {
  const { data } = await api.get<CollaboratorOfferResponse>(
    '/microloans/collaborator/offers/active',
  );
  return data;
}

export async function fetchActiveCollaboratorLoanPlan(): Promise<CollaboratorLoanPlanResponse> {
  const { data } = await api.get<CollaboratorLoanPlanResponse>(
    '/microloans/collaborator/plans/active',
  );
  return data;
}

export async function fetchCollaboratorPayments(): Promise<unknown> {
  const { data } = await api.get<unknown>('/microloans/collaborator/payments');
  return data;
}

export async function simulateCollaboratorOffer(
  offerId: string,
  body: SimulateRequest,
): Promise<SimulateResponse> {
  const { data } = await api.post<SimulateResponse>(
    `/microloans/collaborator/offers/${offerId}/simulate`,
    body,
  );
  return data;
}

export async function acceptCollaboratorOffer(
  offerId: string,
  body: AcceptOfferRequest,
): Promise<AcceptOfferResponse> {
  const { data } = await api.post<AcceptOfferResponse>(
    `/microloans/collaborator/offers/${offerId}/accept`,
    body,
  );
  return data;
}

export async function fetchCollaboratorOfferContractPreview(
  offerId: string,
  params: {
    amount: number;
    installments: number;
    bankAccountNumber?: string;
    bankName?: string;
  },
): Promise<string> {
  const { data } = await api.get<{ markdown: string }>(
    `/microloans/collaborator/offers/${offerId}/contract-preview`,
    {
      params: {
        amount: params.amount,
        installments: params.installments,
        ...(params.bankAccountNumber
          ? { bankAccountNumber: params.bankAccountNumber }
          : {}),
        ...(params.bankName ? { bankName: params.bankName } : {}),
      },
    },
  );
  return data.markdown;
}

export async function fetchCollaboratorPlanContract(
  planId: string,
): Promise<string> {
  const { data } = await api.get<{ markdown: string }>(
    `/microloans/collaborator/plans/${planId}/contract`,
  );
  return data.markdown;
}
