import createClient, { type Middleware } from 'openapi-fetch';
import type { paths } from './schema';
import { config } from '../config';
import { useAuthStore } from '../auth/auth-store';

let getAccessToken: () => string | null = () =>
  useAuthStore.getState().accessToken;
let onUnauthorized: () => void = () => {};
let refreshing: Promise<void> | null = null;

export function configureAuth(opts: {
  getAccessToken?: () => string | null;
  onUnauthorized: () => void;
}) {
  if (opts.getAccessToken) getAccessToken = opts.getAccessToken;
  onUnauthorized = opts.onUnauthorized;
}

const authMiddleware: Middleware = {
  async onRequest({ request }) {
    const token = getAccessToken();
    if (token) {
      request.headers.set('Authorization', `Bearer ${token}`);
    }
    request.headers.set('X-Cameleer-Protocol-Version', '1');
    return request;
  },
  async onResponse({ request, response }) {
    if (response.status === 401 || response.status === 403) {
      // Don't re-trigger for auth endpoints (refresh/login) to avoid loops
      const url = new URL(request.url);
      if (url.pathname.endsWith('/auth/refresh') || url.pathname.endsWith('/auth/login')) {
        return response;
      }
      // Coalesce concurrent 401s into a single refresh attempt
      if (!refreshing) {
        refreshing = (async () => {
          try { onUnauthorized(); } finally { refreshing = null; }
        })();
      }
    }
    return response;
  },
};

export const api = createClient<paths>({ baseUrl: config.apiBaseUrl });
api.use(authMiddleware);
