import { defineStore } from "pinia";
import axios from "axios";

export const useAuthStore = defineStore("auth", {
  state: () => ({
    accessToken: null,
    refreshToken: null,
    user: null,
    permissionsByRole: {},
    currentInstance: null,
    serviceId: null,  // Variável para armazenar o serviceId
  }),

  actions: {
    setServiceId(serviceId) {
      this.serviceId = serviceId;
      localStorage.setItem("serviceId", serviceId);  // Armazena o serviceId no localStorage
    },

    setCurrentInstance(instanceId, instanceName) {
      this.currentInstance = instanceId;
      localStorage.setItem("currentInstance", instanceId);
      console.log(instanceName);
    },

    loadServiceIdFromStorage() {
      const serviceId = localStorage.getItem("serviceId");
      if (serviceId) {
        this.serviceId = serviceId;  // Carrega o serviceId do localStorage
      }
    },

    loadInstanceFromStorage() {
      const instance = localStorage.getItem("currentInstance");
      if (instance) {
        this.currentInstance = instance;
      } else if (this.isLoggedIn) {
        this.setCurrentInstance(1);
      }
    },

    async login(username, password) {
      try {
        const response = await axios.post(
          `${import.meta.env.VITE_API_URL}/auth/login`,
          {
            username,
            password,
          },
          {
            headers: {
              accept: "application/json",
              "Content-Type": "application/json",
            },
          }
          
        );
        

        this.setAuthData(response.data);

        // Verifique se a lista de licenses existe e se há pelo menos um item
        const licenses = response.data.user.licenses;
        if (Array.isArray(licenses) && licenses.length > 0) {
          // Definindo serviceId baseado no primeiro item da lista (ajuste conforme sua lógica)
          const serviceId = licenses[0].service_id;
          if (serviceId) {
            this.setServiceId(serviceId); // Salva no estado do Pinia e no localStorage
            console.log("serviceId após login:", this.serviceId); // Confirma se o serviceId foi setado corretamente
          } else {
            console.log("serviceId não encontrado na primeira licença.");
          }
        } else {
          console.log("Não há licenças ou a lista de licenças está vazia.");
        }

        if (!this.currentInstance) {
          this.setCurrentInstance(1);
        }

        return response.data;
      } catch (error) {
        console.error("Login failed:", error.message);
        throw new Error("Login failed. Check your credentials.");
      }
    },

    async refreshAccessToken() {
      try {
        const response = await axios.post(
          `${import.meta.env.VITE_API_URL}/auth/refresh`,
          {
            refresh_token: this.refreshToken,
          }
        );

        this.setAuthData(response.data);
        return response.data;
      } catch (error) {
        console.error("Token refresh failed:", error.message);
        this.logout();
        window.location.href = "/login";
        throw new Error("Session expired. Please login again.");
      }
    },

    setAuthData(data) {
      this.accessToken = data.access_token;
      this.refreshToken = data.refresh_token;
      this.user = data.user;
      this.permissionsByRole = this.extractPermissionsByRole(
        data.user.permissions
      );

      localStorage.setItem("accessToken", this.accessToken);
      localStorage.setItem("refreshToken", this.refreshToken);
      localStorage.setItem("user", JSON.stringify(this.user));
      localStorage.setItem("auth", "true");
      localStorage.setItem(
        "permissionsByRole",
        JSON.stringify(this.permissionsByRole)
      );
    },

    extractPermissionsByRole(permissions) {
      const permissionsByRole = {};
      permissions.forEach((role) => {
        permissionsByRole[role.service_role_name] = role.permissions.map(
          (permission) => permission.type
        );
      });
      return permissionsByRole;
    },

    loadTokenFromStorage() {
      const storedAccessToken = localStorage.getItem("accessToken");
      const storedRefreshToken = localStorage.getItem("refreshToken");
      const storedUser = localStorage.getItem("user");
      const storedPermissionsByRole = localStorage.getItem("permissionsByRole");
      const instance = localStorage.getItem("currentInstance");

      if (
        storedAccessToken &&
        storedRefreshToken &&
        storedUser &&
        storedPermissionsByRole
      ) {
        this.accessToken = storedAccessToken;
        this.refreshToken = storedRefreshToken;
        this.user = JSON.parse(storedUser);
        this.permissionsByRole = JSON.parse(storedPermissionsByRole);
      }

      if (instance) {
        this.currentInstance = instance;
      } else if (this.isLoggedIn) {
        this.setCurrentInstance(1);
      }
    },

    logout() {
      this.accessToken = null;
      this.refreshToken = null;
      this.user = null;
      this.permissionsByRole = {};
      this.currentInstance = null;
      this.serviceId = null;  // Limpa o serviceId ao sair

      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("user");
      localStorage.removeItem("permissionsByRole");
      localStorage.removeItem("auth");
      localStorage.removeItem("currentInstance");
      localStorage.removeItem("serviceId");  // Remove o serviceId ao sair
    },

    // Carregar valores assim que o store for inicializado
    initialize() {
      this.loadServiceIdFromStorage();
      this.loadInstanceFromStorage();
    }
  },

  getters: {
    isLoggedIn: (state) => !!state.accessToken,
    getPermissionsByRole: (state) => (roleName) =>
      state.permissionsByRole[roleName] || [],
    getInstance: (state) => {
      if (!state.currentInstance) {
        const instanceFromStorage = localStorage.getItem("currentInstance");
        if (instanceFromStorage) {
          return instanceFromStorage;
        }
        return 1;
      }
      return state.currentInstance;
    },
    getServiceId: (state) => state.serviceId,  // Getter para pegar o serviceId
  },
});

// Função para configurar interceptors do axios
const setupAxiosInterceptors = (store) => {
  axios.interceptors.request.use(
    (config) => {
      const token = store.accessToken;
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }

      return config;
    },
    (error) => Promise.reject(error)
  );

  axios.interceptors.response.use(
    (response) => response,
    async (error) => {
      const originalRequest = error.config;

      if (error.response?.status === 401 && !originalRequest._retry) {
        originalRequest._retry = true;

        try {
          await store.refreshAccessToken();
          originalRequest.headers.Authorization = `Bearer ${store.accessToken}`;
          return axios(originalRequest);
        } catch (refreshError) {
          console.error("Refresh token failed. Redirecting to login...");
          store.logout();
          window.location.href = "/login";
          return Promise.reject(refreshError);
        }
      }

      return Promise.reject(error);
    }
  );
};

export const initializeAuth = (store) => {
  setupAxiosInterceptors(store);
  store.initialize();
};
