import axios from "axios";
import { safeLocalStorage } from "@/lib/utils";
import { BACKEND_URL } from "@/config/backend";

let accessToken = safeLocalStorage.getItem('accessToken');
let refreshToken = safeLocalStorage.getItem('refreshToken');

export const setTokens = (newAccessToken: string, newRefreshToken: string) => {
  accessToken = newAccessToken;
  refreshToken = newRefreshToken;
  safeLocalStorage.setItem('accessToken', newAccessToken);
  safeLocalStorage.setItem('refreshToken', newRefreshToken);
};

export const clearTokens = () => {
  accessToken = null;
  refreshToken = null;
  safeLocalStorage.removeItem('accessToken');
  safeLocalStorage.removeItem('refreshToken');
};

export const getAccessToken = () => {
  // Always get the latest token from localStorage
  const token = safeLocalStorage.getItem('accessToken');
  console.log('🔐 [getAccessToken] Token check:', { 
    hasToken: !!token, 
    tokenLength: token?.length || 0,
    tokenStart: token?.substring(0, 20) + '...' || 'No token',
    timestamp: new Date().toISOString(),
    localStorageToken: token,
    moduleToken: accessToken
  });
  if (token) {
    accessToken = token; // Update the module variable
    console.log('🔐 [getAccessToken] Updated module token from localStorage');
    return token; // Return the fresh token from localStorage
  } else {
    console.log('🔐 [getAccessToken] No token found in localStorage');
    return null; // Return null if no token found
  }
};

// Helper function to clear all authentication data
// export const clearAllAuthData = () => {
//   console.log('🧹 Clearing all authentication data...');
//   clearTokens();
//   safeLocalStorage.removeItem('codenuk_user');
//   console.log('✅ All authentication data cleared');
// };

export const getRefreshToken = () => {
  // Always get the latest token from localStorage
  const token = safeLocalStorage.getItem('refreshToken');
  if (token) {
    refreshToken = token; // Update the module variable
  }
  return refreshToken;
};

// Logout function that calls the backend API
export const logout = async () => {
  try {
    const refreshToken = getRefreshToken();
    if (refreshToken) {
      await authApiClient.post('/api/auth/logout', { refreshToken });
    }
  } catch (error) {
    console.error('Logout API call failed:', error);
    // Continue with logout even if API call fails
  } finally {
    // Always clear tokens
    clearTokens();
    // Clear any other user data
    safeLocalStorage.removeItem('codenuk_user');
  }
};

export const authApiClient = axios.create({
  baseURL: BACKEND_URL,
  withCredentials: true,
});

// Add auth token to requests
const addAuthTokenInterceptor = (client: typeof authApiClient) => {
  client.interceptors.request.use(
    (config) => {
      if (accessToken) {
        config.headers = config.headers || {};
        config.headers.Authorization = `Bearer ${accessToken}`;
      }
      return config;
    },
    (error) => Promise.reject(error)
  );
};

// Handle token refresh
const addTokenRefreshInterceptor = (client: typeof authApiClient) => {
  client.interceptors.response.use(
    (response) => response,
    async (error) => {
      const originalRequest = error.config;
      const isRefreshEndpoint = originalRequest?.url?.includes('/api/auth/refresh');
      if (error.response?.status === 401 && !originalRequest._retry && !isRefreshEndpoint) {
        originalRequest._retry = true;
        try {
          if (refreshToken) {
            const response = await client.post('/api/auth/refresh', {
              refreshToken: refreshToken
            });
            const { accessToken: newAccessToken, refreshToken: newRefreshToken } = response.data.data.tokens;
            setTokens(newAccessToken, newRefreshToken);
            originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
            return client(originalRequest);
          }
          // No refresh token available
          clearTokens();
          safeLocalStorage.removeItem('codenuk_user');
          window.location.href = '/signin';
          return Promise.reject(error);
        } catch (refreshError) {
          console.error('Token refresh failed:', refreshError);
          clearTokens();
          safeLocalStorage.removeItem('codenuk_user');
          window.location.href = '/signin';
          return Promise.reject(refreshError);
        }
      }
      return Promise.reject(error);
    }
  );
};

addAuthTokenInterceptor(authApiClient);
addTokenRefreshInterceptor(authApiClient);