import { gql } from '@apollo/client';
import initializeApollo from 'apollo/client';
import { defaultValues } from 'config/tables/insurance-table';
import type * as CRMTypes from 'gql/crm.types';
import type { GetQuoteDataInput, GetQuoteDataOutput } from '../load-kp/types';

const DEFAULT_FINGAP_ROW = defaultValues.find((x) => x.key === 'fingap')!;

const QUERY_GET_RISKS = gql`
  query GetRisksDataFromQuote($quoteId: Uuid!) {
    quote(quoteId: $quoteId) {
      evo_fingap_accountid
      evo_fingap_payer
      evo_fingap_period
      evo_product_risks {
        evo_addproduct_typeid
      }
    }
  }
`;

type QuoteFingapProcessData = {
  insurance: {
    values: Pick<GetQuoteDataOutput['insurance']['values'], 'fingap'>;
  };
  fingap: GetQuoteDataOutput['fingap'];
};

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

  const {
    data: { quote },
  } = await apolloClient.query<
    CRMTypes.GetRisksDataFromQuoteQuery,
    CRMTypes.GetRisksDataFromQuoteQueryVariables
  >({
    query: QUERY_GET_RISKS,
    variables: {
      quoteId,
    },
  });

  const keys: Array<string> = [];
  quote?.evo_product_risks?.forEach((x) => {
    if (x.evo_addproduct_typeid) {
      keys.push(x.evo_addproduct_typeid);
    }
  });

  return {
    fingap: {
      keys,
    },
    insurance: {
      values: {
        fingap: {
          ...DEFAULT_FINGAP_ROW,
          insuranceCompany: quote?.evo_fingap_accountid || null,
          insured: quote?.evo_fingap_payer || null,
          insTerm: quote?.evo_fingap_period || null,
        },
      },
    },
  };
}
