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,
  ): Promise<[AxiosResponse?, string?]> => {
    try {
      const sp = new URLSearchParams([
        ...Object.entries(orderBy),
        ['count', String(count)],
        ['page', String(page)],
        ['input', search],
      ]);
      setURIParams(sp);

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