import { defineStore } from "pinia";
import type { ApiResponse } from "~/types/ApiResponse";
import type { User } from "~/types/User";

export const useUserStore = defineStore("user", {
  state: () => ({
    id: null as number | null,
    nombre: "" as string | undefined,
    role: "" as string | undefined,
    globalLoading: false as boolean | false,
  }),

  getters: {},

  actions: {
    // Obtener la información del usuario en caso de refrescar la página
    async fetchUserInfo() {
      try {
        this.globalLoading = true
        const { data, success } = await useApiFetch<ApiResponse<User>>(
          "user-info",
          {
            method: "POST",
          },
        );
        if (success) {
          this.id = data?.id;
          this.nombre = data?.nombre;
          this.role = data?.role;
        }
      } catch (err) {
        console.error("Error fetching user info:", err);
      } finally {
        this.globalLoading = false
      }
    },

    // Guardar toda la info tras el login
    setUserInfo({ nombre, role }: { nombre: string; role: string }) {
      this.nombre = nombre;
      this.role = role;
    },
    // Limpiar el store al cerrar sesión
    async logout() {
      try {
        const { data, success } = await useApiFetch<ApiResponse<User>>(
          "logout",
          {
            method: "POST",
          },
        );
        if (success) {
          const token = useCookie("crm_token");
          token.value = null;
          this.nombre = "";
          this.role = "";
          navigateTo("/login");
        }
      } catch (err) {
        console.error("Error fetching user info:", err);
      }
    },
  },
});
