import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { QueryParams } from '@/components/v2/DataTable/DataTable.vue.d';
import { buildBodyParams } from '@/utils';

export interface ServiceOptions {
  headers?: Record<string, unknown>;
  params?: Record<string, unknown>;
}

export type AssetNameOptionsQueryParams = {
  nameOptions?: boolean;
  brandOptions?: boolean;
};

export type GetAssetNameListQueryParams = {
  assetName?: string;
  tagType?: string;
  category?: string;
  excludeIds?: string[];
};

export interface AssetNameDropdownOption {
  _id: string;
  key: number;
  name: string;
  category: {
    _id: string;
    name: string;
    key: number;
  };
  tagType: string;
}

export interface GetAssetNameDropdownResponse {
  data: AssetNameDropdownOption[];
}

export const API = ({
  headers = {},
  params = {},
}: ServiceOptions = {}): AxiosInstance => {
  const user = JSON.parse(localStorage.getItem('user') ?? '{}');
  const BASE_URL = import.meta.env.VITE_APP_TAGSAMURAI_API;

  const instance = axios.create({
    baseURL: `${BASE_URL}/fam/settings-attribute/v2/asset-name`,
    headers: {
      'Content-type': 'application/json',
      'Authorization': `Bearer ${user.token}`,
      ...headers,
    },
    params,
  });

  return instance;
};

const getAssetNameDetail = (id: string): Promise<AxiosResponse> => {
  return API().get(`/${id}`);
};

const getAssetsByAssetName = (
  id: string,
  params?: QueryParams,
): Promise<AxiosResponse> => {
  return API({ params }).get(`/${id}/list-asset`);
};

const getAssetNameList = (
  params: GetAssetNameListQueryParams,
): Promise<AxiosResponse> => {
  return API({ params }).get('/');
};

const getUnpairedAssetName = (
  params: GetAssetNameListQueryParams,
): Promise<AxiosResponse> => {
  return API({ params }).get('/unpaired');
};

const getOptions = (
  params: AssetNameOptionsQueryParams,
): Promise<AxiosResponse> => {
  return API({ params }).get('/options');
};

const getAssetNameDropdown = (): Promise<
  AxiosResponse<GetAssetNameDropdownResponse>
> => {
  return API().get('/dropdown');
};

const postAssetNameList = (
  params?: GetAssetNameListQueryParams,
): Promise<AxiosResponse> => {
  const body = buildBodyParams(params);
  return API().post('/list', body);
};

export default {
  getAssetNameDetail,
  getAssetNameList,
  getAssetsByAssetName,
  getUnpairedAssetName,
  getAssetNameDropdown,
  getOptions,
  postAssetNameList,
};
