import axios from 'axios';
import { getAuthCallbacks } from './api';
import type { AuthResponse } from '@/types/api';

// Base URL: /media (Vite proxy → Fastify 4100)
export const mediaApi = axios.create({
  baseURL: '/media',
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // Send httpOnly cookies with requests
});

// Request interceptor: attach Bearer token from auth store
mediaApi.interceptors.request.use(
  (config) => {
    const callbacks = getAuthCallbacks();
    const accessToken = callbacks.getAccessToken();
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor: handle 401 with token refresh
let mediaRefreshPromise: Promise<AuthResponse> | null = null;

mediaApi.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    const errorCode = error.response?.data?.error?.code;

    // Handle 401 errors with proper error code checking
    if (
      error.response?.status === 401 &&
      (errorCode === 'INVALID_TOKEN' || errorCode === 'AUTH_REQUIRED') &&
      !originalRequest._retry
    ) {
      originalRequest._retry = true;

      const callbacks = getAuthCallbacks();

      try {
        // Use shared refresh promise to prevent concurrent refreshes
        if (!mediaRefreshPromise) {
          // Refresh token sent automatically as httpOnly cookie
          const { api } = await import('./api');

          mediaRefreshPromise = api
            .post<AuthResponse>('/auth/refresh')
            .then((res) => res.data)
            .finally(() => {
              mediaRefreshPromise = null;
            });
        }

        const data = await mediaRefreshPromise;

        // Update access token in auth store via callback
        callbacks.onTokenRefresh(data.accessToken!);

        // Retry original request with new token
        originalRequest.headers.Authorization = `Bearer ${data.accessToken}`;
        return mediaApi(originalRequest);
      } catch (refreshError) {
        // Refresh failed - clear auth state and trigger redirect
        callbacks.onAuthFailure();
        return Promise.reject(error);
      }
    }

    return Promise.reject(error);
  }
);
