import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { SystemRoleAttribute, TransactionAttribute } from '@/utils/role.util';
import { TreeNode } from 'primevue/treenode';

export interface ServiceOptions {
  type?: 'Group' | 'Category';
  headers?: Record<string, unknown>;
  params?: TreeQueryParams;
}

export interface TreeListData {
  data: TreeNode[];
}

export type RoleType = 'Manager' | 'Monitoring' | 'Approval' | 'Staff';

export interface TreeRoleParams {
  showAll?: boolean;
  systemRole?: SystemRoleAttribute[];
  transactionAttribute?: TransactionAttribute[];
  roleType?: RoleType[];
}

export interface TreeQueryParams {
  systemRole?: string;
  transactionAttribute?: string;
  roleType?: string;
  showAll?: boolean;
}

export const API = ({
  type = 'Group',
  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/`,
    headers: {
      'Content-type': 'application/json',
      'Authorization': `Bearer ${user.token}`,
      ...headers,
    },
    params,
  });

  return instance;
};

const TreeServices = {
  getTreeList: (
    type: ServiceOptions['type'],
    params?: TreeQueryParams,
  ): Promise<AxiosResponse<TreeListData>> => {
    return API({ type, params }).get(
      type === 'Group' ? '/groups/tree' : '/category/tree',
    );
  },
  getGroups: async (params: any, id: string): Promise<AxiosResponse> => {
    return API({ params }).get('/groups/6729e0e83e3254d4b302c3b6');
  },
};

export default TreeServices;
