import {
  Person,
  PersonalAccountApi,
  PersonStatusEnum,
  Response,
} from '@/openapi/personal-accounts';
import { notifyError } from '@/utils/notify';
import { searchByFieldInList } from '@/utils/query';
import axios from 'axios';
import has from 'lodash/has';

export const personalAccountApi = new PersonalAccountApi();

function hasExternalLinks(acc: Person) {
  return has(acc, 'personrelation') || has(acc, 'personapplication');
}

export async function getAccountsByIds(ids: string[], expend = 'personapplication'): Promise<Person[]> {
  try {
    const { data } = await personalAccountApi.searchPerson(
      searchByFieldInList('id', ids),
      '',
      '+modified',
      expend
    );
    return data;
  } catch (error) {
    if (!axios.isAxiosError(error)) {
      throw error;
    }
    return [];
  }
}

export async function deletePersonalAccounts(ids: string[]): Promise<Response[]> {
  const idsToDelete: string[] = [];
  const impossibleToDelete: string[] = [];
  (await getAccountsByIds(ids)).forEach((acc) => {
    if (
      hasExternalLinks(acc) ||
      (
        acc.status !== PersonStatusEnum.New &&
        acc.status !== PersonStatusEnum.Draft &&
        acc.status !== PersonStatusEnum.NotConfirmed
      )
    ) {
      impossibleToDelete.push(`'${acc.fullName}'`);
    } else {
      idsToDelete.push(`${acc.id}`);
    }
  });

  if (impossibleToDelete.length) {
    notifyError(
      `Невозможно удалить личные дела: ${impossibleToDelete.join(', ')}`
    );
  }
  if (!idsToDelete.length) {
    return [
      {
        success: false,
        message: 'Ничего не удалено',
      },
    ];
  }
  return Promise.all(idsToDelete.map(async (id) => {
    const { data } = await personalAccountApi.deleteByIdPerson(id);
    return data;
  }))
}