import axios from "axios";
import { safeLocalStorage, safeRedirect } from "@/lib/utils";

const API_BASE_URL = "http://localhost:8011";

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 = () => accessToken;
export const getRefreshToken = () => 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 and redirect
    clearTokens();
    // Clear any other user data
    safeLocalStorage.removeItem('codenuk_user');
    // Redirect to signin page
    safeRedirect('/signin');
  }
};

export const authApiClient = axios.create({
  baseURL: API_BASE_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;
      if (error.response?.status === 401 && !originalRequest._retry) {
        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);
          }
        } catch (refreshError) {
          console.error('Token refresh failed:', refreshError);
          clearTokens();
          window.location.href = '/auth';
          return Promise.reject(refreshError);
        }
      }
      return Promise.reject(error);
    }
  );
};

addAuthTokenInterceptor(authApiClient);
addTokenRefreshInterceptor(authApiClient);