import { $axios } from '@/plugins/axios';
import { AxiosResponse } from 'axios';
import { OrderBy } from '@/types/order-by';
import { camelToSnake } from '@/mixins/case-converter';
import { setURIParams } from '@/mixins/query-params';

export default {
  getAll: async (
    count: number = 10,
    page: number = 1,
    orderBy: OrderBy,
    search: string,
    groupId: string,
  ): Promise<[AxiosResponse?, string?]> => {
    try {
      const sp = new URLSearchParams([
        ...Object.entries(orderBy),
        ['count', String(count)],
        ['page', String(page)],
        ['input', search],
        ['group_id', groupId],
      ]);
      setURIParams(sp);

      const params: string = camelToSnake(sp.toString());
      const data = await $axios.get(`v1/users?${params}`);
      return [data, undefined];
    } catch (e: any) {
      return [undefined, e?.response?.data?.error ?? e.message];
    }
  },
  create: async (
    email: string,
    realName: string,
    groupID: number,
  ): Promise<[AxiosResponse?, string?]> => {
    try {
      const data = await $axios.post('v1/users', {
        email,
        realName,
        groupID,
      });
      return [data, undefined];
    } catch (e: any) {
      return [undefined, e?.response?.data?.error ?? e.message];
    }
  },
  update: async (
    ID: number,
    email: string,
    realName: string,
    groupID: number,
  ): Promise<[AxiosResponse?, string?]> => {
    try {
      const data = await $axios.patch('v1/users', {
        ID,
        email,
        realName,
        groupID,
      });
      return [data, undefined];
    } catch (e: any) {
      return [undefined, e?.response?.data?.error ?? e.message];
    }
  },
};
