import axios from 'axios';

// Client for the new Doormile Express admin API (api.doormile.com/api/v1/admin/*).
// Separate instance from utils/axios.js and the raw axios calls in pages/api/api.js
// because this backend requires a JWT Bearer token on every request and uses its
// own token lifecycle — it does not share the `authname` gate in App.js.
// See express-console-api.md at the repo root for the full endpoint reference.

export const DOORMILE_TOKEN_KEY = 'doormileToken';
export const DOORMILE_USER_KEY = 'doormileUser';

const doormileAxios = axios.create({
  baseURL: process.env.REACT_APP_DOORMILE_URL || 'https://api.doormile.com/api/v1'
});

doormileAxios.interceptors.request.use((config) => {
  const token = localStorage.getItem(DOORMILE_TOKEN_KEY);
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

doormileAxios.interceptors.response.use(
  (response) => response,
  (error) => {
    // Mirror utils/session.js's performSessionLogout contract (full localStorage
    // wipe + hard navigate) so an expired doormile token logs the console out the
    // same way inactivity/manual logout does, instead of leaving a half-authed state.
    if (error.response?.status === 401 && !window.location.href.includes('/login')) {
      localStorage.clear();
      window.location.replace('/login');
    }
    return Promise.reject(error.response?.data || error);
  }
);

export default doormileAxios;
