import { type QueryClient } from 'react-query';

export const microloansKeys = {
  all: () => ['microloans'] as const,
  collaboratorStatus: () =>
    [...microloansKeys.all(), 'collaborator-status'] as const,
  finishedLoans: () => [...microloansKeys.all(), 'finished-loans'] as const,
  lists: () => [...microloansKeys.all(), 'list'] as const,
  list: (filters: string) => [...microloansKeys.lists(), { filters }] as const,
  details: () => [...microloansKeys.all(), 'detail'] as const,
  detail: (id: string) => [...microloansKeys.details(), id] as const,
  loanOffer: () => [...microloansKeys.all(), 'loan-offer'] as const,
  activeLoanPlan: () => [...microloansKeys.all(), 'active-loan-plan'] as const,
  collaboratorPayments: () =>
    [...microloansKeys.all(), 'collaborator-payments'] as const,
  simulate: (offerId: string, amount: number, weeks: number) =>
    [...microloansKeys.all(), 'simulate', offerId, amount, weeks] as const,
  contractPreview: (
    offerId: string,
    amountCentavos: number,
    installments: number,
    bankAccountNumber = '',
    bankName = '',
  ) =>
    [
      ...microloansKeys.all(),
      'contract-preview',
      offerId,
      amountCentavos,
      installments,
      bankAccountNumber,
      bankName,
    ] as const,
  planContract: (planId: string) =>
    [...microloansKeys.all(), 'plan-contract', planId] as const,
};

const POST_ACCEPT_INVALIDATION_EXCLUDED: ReadonlySet<string> = new Set([
  'loan-offer',
  'simulate',
  'contract-preview',
]);

export function invalidateMicroloansAfterAcceptOffer(
  queryClient: QueryClient,
): void {
  void queryClient.invalidateQueries(microloansKeys.all(), {
    predicate: query => {
      const k = query.queryKey;
      return (
        Array.isArray(k) &&
        k[0] === 'microloans' &&
        typeof k[1] === 'string' &&
        !POST_ACCEPT_INVALIDATION_EXCLUDED.has(k[1])
      );
    },
  });
}
