import api from '@/api';
import { validName } from '@/mixins/validator';
import { GroupForm, Group } from '@/types/group';
import { getAll } from '../users/search';

//
// MARK: Creation group
//
const createModal: Ref<boolean> = ref(false);
const loadingCreate: Ref<boolean> = ref(false);
const errorCreate: Ref<string> = ref('');
const form: Ref<Partial<GroupForm>> = ref({
  ID: 0,
  name: '',
  permissions: [],
});
const createGroup = async () => {
  if (
    loadingCreate.value ||
    !form.value.name ||
    !validName(form.value.name) ||
    !form.value.permissions
  ) {
    return;
  }

  resetErrorCreate();
  setLoadingCreate(true);

  const [_, e] = await api.groups.create(
    form.value.name,
    form.value.permissions,
  );
  if (e && typeof e === 'string') {
    errorCreate.value = e;
  } else {
    closeModal();
    getAll();
  }

  setLoadingCreate(false);
};
const resetErrorCreate = () => (errorCreate.value = '');
const openModal = () => {
  setDefaultForm();
  setIsEditing(false);
  createModal.value = true;
};
const closeModal = () => (createModal.value = false);
const setLoadingCreate = (state: boolean) => (loadingCreate.value = state);
const setDefaultForm = () =>
  (form.value = {
    ID: 0,
    name: '',
    permissions: [],
  });

//
// MARK: Edit group
//
const isEditing: Ref<boolean> = ref(false);
const editGroup = async () => {
  if (
    loadingCreate.value ||
    !form.value.ID ||
    !form.value.name ||
    !validName(form.value.name) ||
    !form.value.permissions
  ) {
    return;
  }

  resetErrorCreate();
  setLoadingCreate(true);

  const [_, e] = await api.groups.update(
    form.value.ID,
    form.value.name,
    form.value.permissions,
  );
  if (e && typeof e === 'string') {
    errorCreate.value = e;
  } else {
    closeModal();
    getAll();
  }

  setLoadingCreate(false);
};
const startEditGroup = async (g: Group) => {
  setIsEditing(true);

  form.value = {
    ID: g.ID,
    name: g.name,
    permissions: g.permissions?.map((i) => i.value),
  };
};
const setIsEditing = (state: boolean) => (isEditing.value = state);

export {
  createModal,
  loadingCreate,
  errorCreate,
  form,
  createGroup,
  resetErrorCreate,
  openModal,
  closeModal,
  setLoadingCreate,
  setDefaultForm,
  isEditing,
  editGroup,
  startEditGroup,
  setIsEditing,
};
