import axios from 'axios';

const TOKEN_KEY = 'cpas_token';

export function getToken()    { return localStorage.getItem(TOKEN_KEY); }
export function setToken(t)   { localStorage.setItem(TOKEN_KEY, t); }
export function clearToken()  { localStorage.removeItem(TOKEN_KEY); }

// Attach the session token to every outgoing request.
axios.interceptors.request.use((config) => {
  const token = getToken();
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// When the server rejects a token (expired / invalid), drop it and notify the
// app so it can fall back to the login screen.
let onUnauthorized = null;
export function setUnauthorizedHandler(fn) { onUnauthorized = fn; }

axios.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response && err.response.status === 401) {
      clearToken();
      if (onUnauthorized) onUnauthorized();
    }
    return Promise.reject(err);
  }
);
