import axios from 'axios';

interface NsiRegistryPagination<T extends NsiRegistryDocument> {
  filter: string;
  totalRows: number;
  page: number;
  perPage: number;
  records: T[];
  schema: string;
  foundRows: number;
}

interface NsiRegistryDocument {
  id: string;
  modified: number;
  schema: string;
}
export interface FpsDocument extends NsiRegistryDocument {
  schedule: string;
  address: string;
  code: string;
  shouldSync: boolean;
  phone: string;
  format: string;
  typeFPS: string;
  attemptCount: number;
  autokey: string;
  title: string;
  codeFPS: string;
}
export interface FpsOfficeDocument extends NsiRegistryDocument {
  address: string;
  code: string;
  attemptCount: string;
  autokey: string;
  officeHours: string;
  title: string;
  type: string;
  numberShortVisitOfficial: string;
  schedule: string;
  shouldSync: string;
  numberLongVisit: string;
  numberShortVisitRelative: string;
  OKATO: string;
}

/**
 *
 * @export
 */
export const setSearchParams = function (
  url: URL,
  ...objects: Record<string, any>[]
): void {
  const searchParams = new URLSearchParams(url.search);
  for (const object of objects) {
    for (const key in object) {
      if (Array.isArray(object[key])) {
        searchParams.delete(key);
        for (const item of object[key]) {
          searchParams.append(key, item);
        }
      } else {
        searchParams.set(key, object[key]);
      }
    }
  }
  url.search = searchParams.toString();
};

/**
 *
 * @export
 */
export const toPathString = function (url: URL): string {
  return url.pathname + url.search + url.hash;
};

const localVarPath = '/service/nsi-registry/registry';
const noFounfErrorMessage = 'Не найдено';

export async function searchRegistryBy<T extends NsiRegistryDocument>(
  registryId: string,
  page?: number,
  perPage?: number,
  filter?: string,
  sort?: string,
  options: any = {}
): Promise<NsiRegistryPagination<T>> {
  const localVarUrlObj = new URL(
    `${localVarPath}/${registryId}`,
    'https://example.com'
  );
  const localVarRequestOptions = { method: 'GET', ...options };
  const localVarQueryParameter = {} as any;

  if (page !== undefined) {
    localVarQueryParameter.page = page;
  }

  if (perPage !== undefined) {
    localVarQueryParameter.perPage = perPage;
  }

  if (filter !== undefined) {
    localVarQueryParameter.filter = filter;
  }

  if (sort !== undefined) {
    localVarQueryParameter.sort = sort;
  }

  setSearchParams(localVarUrlObj, localVarQueryParameter);

  try {
    const { data } = await axios.get<NsiRegistryPagination<T>>(
      toPathString(localVarUrlObj)
    );
    if (!data?.records.length) {
      throw Error(noFounfErrorMessage);
    }
    return data;
  } catch (e) {
    throw Error(noFounfErrorMessage);
  }
}
