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,
    service_instance_id: null,
    userId: null,
    serviceRoleId: null // <- Novo campo
  }),

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

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

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

    loadServiceInstanceFromStorage() {
      const instance = localStorage.getItem("currentInstance");
      if (instance) {
        this.currentInstance = instance;
      }
    
      const storedServiceInstanceId = localStorage.getItem("serviceInstanceId");
      if (storedServiceInstanceId) {
        this.service_instance_id = storedServiceInstanceId;
        console.log("✅ service_instance_id carregado do localStorage:", this.service_instance_id);
      } else {
        console.log("⚠️ Nenhum service_instance_id encontrado no localStorage.");
      }
    
      if (!this.currentInstance && this.isLoggedIn) {
        this.setCurrentInstance(1);
      }

    },
    loadUserIdFromStorage(){
      const userId = localStorage.getItem("userId");
      if (userId) {
        this.userId = userId;
      }

    },
    
    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.user = response.data.user;
        this.token = response.data.token;
    
        console.log("🔎 Dados recebidos do backend:", response.data);
    
        // ✅ Captura e armazena o service_role_id, se desejar
        this.serviceRoleId = response.data.user.service_role_id;
        localStorage.setItem("serviceRoleId", this.serviceRoleId);
        
        // ✅ Captura e armazena o id do usuario, se desejar
        this.userId = response.data.user.id;
        localStorage.setItem("userId", this.userId)        
        console.log("✅ userid salvo", this.userId);
    
        // ✅ Captura e armazena o service_instance_id a partir do primeiro permission
        const firstPermission = response.data.user.permissions?.[0];
        if (firstPermission?.service_instance_id) {
          this.service_instance_id = firstPermission.service_instance_id;
          localStorage.setItem("serviceInstanceId", this.service_instance_id);
          console.log("✅ service_instance_id salvo do primeiro permission:", this.service_instance_id);
        } else {
          console.warn("⚠️ Nenhum service_instance_id encontrado nos permissions.");
        }
    
        this.setAuthData(response.data);
    
        const licenses = response.data.user.licenses;
        if (Array.isArray(licenses) && licenses.length > 0) {
          const serviceId = licenses[0].service_id;
          if (serviceId) {
            this.setServiceId(serviceId);
            console.log("serviceId após login:", this.serviceId);
          } 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);
      }

      // ✅ Carrega o service_role_id do localStorage
      const storedServiceRoleId = localStorage.getItem("serviceRoleId");
      if (storedServiceRoleId) {
        this.serviceRoleId = storedServiceRoleId;
      }
    },

    logout() {
      this.accessToken = null;
      this.refreshToken = null;
      this.user = null;
      this.permissionsByRole = {};
      this.currentInstance = null;
      this.serviceId = null;
      this.serviceRoleId = null; // <- Limpa o valor
      this.userId = null;

      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("user");
      localStorage.removeItem("permissionsByRole");
      localStorage.removeItem("auth");
      localStorage.removeItem("currentInstance");
      localStorage.removeItem("serviceId");
      localStorage.removeItem("serviceRoleId"); // <- Remove do storage
    },

    initialize() {
      this.loadServiceIdFromStorage();
      this.loadInstanceFromStorage();
      this.loadServiceInstanceFromStorage();
      this.loadUserIdFromStorage();

    }
  },

  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,
    getServiceRoleId: (state) => state.serviceRoleId // <- Novo getter
  },
});

// 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();
};
