/**
 * Base axios client for the Effigenix API
 */

import axios, { type AxiosInstance } from 'axios';
import { type ApiConfig, DEFAULT_API_CONFIG } from '@effigenix/config';
import { setupAuthInterceptor } from './interceptors/auth-interceptor.js';
import { setupRefreshInterceptor } from './interceptors/refresh-interceptor.js';
import { setupErrorInterceptor } from './interceptors/error-interceptor.js';
import type { TokenProvider } from './token-provider.js';

export type { AxiosInstance };

/**
 * Creates and configures an axios instance with all interceptors.
 *
 * @param config - Optional API configuration (defaults to localhost:8080)
 * @param tokenProvider - Provides access/refresh tokens and handles token storage
 */
export function createApiClient(
  config: Partial<ApiConfig> = {},
  tokenProvider: TokenProvider,
): AxiosInstance {
  const resolvedConfig: ApiConfig = { ...DEFAULT_API_CONFIG, ...config };

  const client = axios.create({
    baseURL: resolvedConfig.baseUrl,
    timeout: resolvedConfig.timeoutMs,
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
  });

  setupAuthInterceptor(client, tokenProvider);
  setupRefreshInterceptor(client, tokenProvider);
  setupErrorInterceptor(client);

  return client;
}
