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

export const useRoleStore = defineStore("role", {
  state: () => {
    return {
      roles: [] as Array<RoleViewModel>,
      loading: null as null | "loading" | "success" | "failed",
    };
  },
  actions: {
    fetchRoles() {
      this.loading = "loading";
      http
        .get("/admin/role")
        .then((result) => {
          this.roles = result.data;
          this.loading = "success";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchRoleById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/role/${id}`);
    },
    async createRole(role: string): Promise<AxiosResponse<any, any>> {
      const result = await http.post("/admin/role", {
        role: role,
      });
      this.fetchRoles();
      return result;
    },
    async updateActiveRole(id: number, role: string): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/role/${id}`, {
        role: role,
      });
      this.fetchRoles();
      return result;
    },
    async updateActiveRolePermissions(role: number, permission: PermissionObject): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/role/${role}/permissions`, {
        permissions: permission,
      });
      this.fetchRoles();
      return result;
    },
    async deleteRole(role: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/role/${role}`);
      this.fetchRoles();
      return result;
    },
  },
});
