import { defineStore } from "pinia";
import type { RoleViewModel } from "../../viewmodels/admin/role.models";
import { http } from "../../serverCom";

export const useRoleStore = defineStore("role", {
  state: () => {
    return {
      roles: [] as Array<RoleViewModel>,
      role: null as null | RoleViewModel,
      loadingAll: null as null | "loading" | "success" | "failed",
      loadingSingle: null as null | "loading" | "success" | "failed",
      createStatus: null as null | "loading" | { status: "success" | "failed"; reason?: string },
    };
  },
  actions: {
    fetchRoles() {
      this.loadingAll = "loading";
      http
        .get("/admin/role")
        .then((result) => {
          this.roles = result.data;
          this.loadingAll = "success";
        })
        .catch((err) => {
          this.loadingAll = "failed";
        });
    },
    fetchRolesById(id: number) {
      this.role = null;
      this.loadingSingle = "loading";
      http
        .get(`/admin/role/${id}`)
        .then((result) => {
          this.role = result.data;
          this.loadingSingle = "success";
        })
        .catch((err) => {
          this.loadingSingle = "failed";
        });
    },
    resetCreateStatus() {
      this.createStatus = null;
    },
    createRole(role: string) {
      this.createStatus = "loading";
      http
        .post("/admin/role", {
          role: role,
        })
        .then((res) => {
          this.createStatus = { status: "success" };
          this.fetchRoles();
        })
        .catch((err) => {
          this.createStatus = { status: "failed", reason: err.data };
        });
    },
  },
});