import useMember from "./useMember";

export default function useRole() {
  function createRole(
    { name, permissions, type, org, site, platform } = {} as {
      name: string;
      permissions: Array<string>;
      type: string;
      org?: string;
      site?: string;
      platform?: string;
    }
  ) {
    return useNuxtApp().$api("/api/roles", {
      method: "POST",
      body: { name, permissions, type, org, site, platform },
    });
  }

  function getRoles({
    search = "",
    page = 1,
    limit = 20,
    type = "",
    org = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>("/api/roles", {
      method: "GET",
      query: { search, page, limit, type, org },
    });
  }

  function getRoleById(id: string) {
    return useNuxtApp().$api<TRole>(`/api/roles/id/${id}`, {
      method: "GET",
    });
  }

  function updateRoleById(
    _id: string,
    name?: string,
    permissions?: Array<string>
  ) {
    return useNuxtApp().$api(`/api/roles/id/${_id}`, {
      method: "PATCH",
      body: { name, permissions },
    });
  }

  function updatePermissionById(_id: string, permissions?: Array<string>) {
    return useNuxtApp().$api(`/api/roles/permissions/id/${_id}`, {
      method: "PATCH",
      body: { permissions },
    });
  }

  function updateRoleFieldById(_id: string, field: string, value: string) {
    return useNuxtApp().$api(`/api/roles/${_id}`, {
      method: "PATCH",
      body: { field, value },
    });
  }

  function deleteRole(_id: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/roles/deleted/role`, {
      method: "PUT",
      query: { id: _id },
    });
  }

  const role = useState<TRole>("userRole", () => {
    return {
      _id: "",
      name: "",
      permissions: [],
      description: "",
      createdAt: "",
      updatedAt: "",
      deletedAt: "",
    };
  });

  const { getByUserId } = useMember();

  async function getRoleByUserId(user: string) {
    const member = ref<TMember | null>(null);

    try {
      const res = await getByUserId(user);
      member.value = res;
      const _role = await getRoleById(res.role);
      Object.assign(role.value, _role);
    } catch (error) {
      console.log(error);
    }
  }

  return {
    role,
    createRole,
    getRoles,
    getRoleById,
    updateRoleById,
    updateRoleFieldById,
    deleteRole,
    updatePermissionById,
    getRoleByUserId,
  };
}
