import { useQuery } from '@vue/apollo-composable';
import { MyCounterpartyProfileDocument } from '~/composables/graphql/generated';

function hasText(value: string | null | undefined) {
  return Boolean(value && value.trim().length > 0);
}

export function isCounterpartyProfileComplete(profile: {
  companyName?: string | null;
  companyFullName?: string | null;
  inn?: string | null;
  legalAddress?: string | null;
  bankName?: string | null;
  bik?: string | null;
  correspondentAccount?: string | null;
  checkingAccount?: string | null;
  signerFullName?: string | null;
  signerPosition?: string | null;
  signerBasis?: string | null;
} | null | undefined) {
  if (!profile) {
    return false;
  }

  return [
    profile.companyName,
    profile.companyFullName,
    profile.inn,
    profile.legalAddress,
    profile.bankName,
    profile.bik,
    profile.correspondentAccount,
    profile.checkingAccount,
    profile.signerFullName,
    profile.signerPosition,
    profile.signerBasis,
  ].every(hasText);
}

export function useCounterpartyProfile() {
  const query = useQuery(MyCounterpartyProfileDocument);

  const profile = computed(() => query.result.value?.myCounterpartyProfile ?? null);
  const isComplete = computed(() => isCounterpartyProfileComplete(profile.value));

  return {
    profile,
    isComplete,
    loading: query.loading,
    error: query.error,
    refetch: query.refetch,
  };
}
