/* eslint-disable @typescript-eslint/naming-convention */
import { gql } from '@apollo/client';
import initializeApollo from 'apollo/client';
import type * as CRMTypes from 'gql/crm.types';
import { sort } from 'radash';
import type { GetQuoteDataInput, GetQuoteDataOutput } from '../load-kp/types';

const QUERY_GET_PAYMENTS_DATA_FROM_QUOTE = gql`
  query GetPaymentsDataFromQuote($quoteId: Uuid!) {
    quote(quoteId: $quoteId) {
      evo_period
      evo_accept_period
      evo_first_payment_perc
      evo_last_payment_perc
      evo_graph_type
      evo_payments_decrease_perc
      evo_seasons_type
      evo_high_season
      evo_graphs {
        createdon
        evo_sumpay_withnds
        evo_planpayments {
          evo_payment_ratio
        }
      }
    }
  }
`;

type QuotePaymentsProcessData = {
  values: Partial<GetQuoteDataOutput['values']>;
  payments: GetQuoteDataOutput['payments'];
};

export default async function getPaymentsDataFromKP({
  values: { quote: quoteId, recalcWithRevision },
}: GetQuoteDataInput): Promise<QuotePaymentsProcessData> {
  const apolloClient = initializeApollo();

  const {
    data: { quote },
  } = await apolloClient.query<
    CRMTypes.GetPaymentsDataFromQuoteQuery,
    CRMTypes.GetPaymentsDataFromQuoteQueryVariables
  >({
    query: QUERY_GET_PAYMENTS_DATA_FROM_QUOTE,
    variables: {
      quoteId,
    },
  });

  const leasingPeriod = recalcWithRevision
    ? Math.min(quote?.evo_period ?? 0, quote?.evo_accept_period ?? 0)
    : quote?.evo_period ?? 0;

  let paymentsValues: Array<number> = [];
  if (quote?.evo_graphs) {
    paymentsValues =
      sort(quote?.evo_graphs, (evo_graph) => Date.parse(evo_graph?.createdon))
        .at(0)
        ?.evo_planpayments?.slice(1, -1)
        .slice(0, leasingPeriod - 2)
        .map((payment) => payment?.evo_payment_ratio || 0) || [];
  }

  return {
    values: {
      leasingPeriod,
      graphType: quote?.evo_graph_type ?? undefined,
      parmentsDecreasePercent: quote?.evo_payments_decrease_perc || 0,
      highSeasonStart: quote?.evo_high_season,
      seasonType: quote?.evo_seasons_type,
      firstPaymentPerc: quote?.evo_first_payment_perc || 0,
      lastPaymentPerc: quote?.evo_last_payment_perc || 0,
    },
    payments: {
      values: [
        quote?.evo_first_payment_perc || 0,
        ...paymentsValues,
        quote?.evo_last_payment_perc || 0,
      ],
    },
  };
}
