import { appApi } from 'src/boot/axios';
import { ref, computed } from 'vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { i18n } from 'boot/lang';
import type { Roles } from 'src/vueLib/models/roles';

export const roles = ref<Roles>([]);

export function useRoleTable() {
  const pagination = ref({
    sortBy: 'role',
    descending: false,
    page: 1,
    rowsPerPage: 10,
  });

  const columns = computed(() => [
    {
      name: 'id',
      align: 'left' as const,
      label: 'Id',
      field: 'id',
      sortable: true,
      style: 'width: 50px; max-width: 50px;',
    },
    {
      name: 'role',
      align: 'left' as const,
      label: i18n.global.t('role'),
      field: 'role',
      sortable: true,
    },
    {
      name: 'rights',
      align: 'left' as const,
      label: i18n.global.t('rights'),
      field: 'rights',
      sortable: true,
      style: 'width: 120px; max-width: 120px;',
    },
    { name: 'option', align: 'center' as const, label: '', field: 'option', icon: 'option' },
  ]);

  const { NotifyResponse } = useNotify();

  const loading = ref(false);

  //updates user list from database
  function updateRoles() {
    loading.value = true;
    appApi
      .get('secure/roles')
      .then((resp) => {
        if (resp.data === null) {
          roles.value = [];
          return;
        }
        roles.value = resp.data as Roles;
        if (roles.value === null) {
          roles.value = [];
          return;
        }
      })

      .catch((err) => {
        NotifyResponse(err, 'error');
      })
      .finally(() => {
        loading.value = false;
      });
  }
  return {
    roles,
    pagination,
    columns,
    loading,
    updateRoles,
  };
}
