import { defineStore } from "pinia";
import type { UpdateUserViewModel, UserViewModel } from "@/viewmodels/admin/user/user.models";
import { http } from "@/serverCom";
import type { PermissionObject } from "@/types/permissionTypes";
import type { AxiosResponse } from "axios";

export const useUserStore = defineStore("user", {
  state: () => {
    return {
      users: [] as Array<UserViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchUsers() {
      this.loading = "loading";
      http
        .get("/admin/user")
        .then((result) => {
          this.users = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchUserById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/user/${id}`);
    },
    updateActiveUser(user: UpdateUserViewModel): Promise<AxiosResponse<any, any>> {
      return http
        .patch(`/admin/user/${user.id}`, {
          username: user.username,
          firstname: user.firstname,
          lastname: user.lastname,
          mail: user.mail,
        })
        .then((result) => {
          this.fetchUsers();
          return result;
        });
    },
    updateActiveUserPermissions(user: number, permission: PermissionObject): Promise<AxiosResponse<any, any>> {
      return http
        .patch(`/admin/user/${user}/permissions`, {
          permissions: permission,
        })
        .then((result) => {
          this.fetchUsers();
          return result;
        });
    },
    updateActiveUserRoles(user: number, roles: Array<number>): Promise<AxiosResponse<any, any>> {
      return http
        .patch(`/admin/user/${user}/roles`, {
          roleIds: roles,
        })
        .then((result) => {
          this.fetchUsers();
          return result;
        });
    },
    deleteUser(user: number): Promise<AxiosResponse<any, any>> {
      return http.delete(`/admin/user/${user}`).then((result) => {
        this.fetchUsers();
        return result;
      });
    },
  },
});
