import axios from 'axios';
import { getAuthCallbacks } from './api';

/**
 * Public Media API Client
 * For unauthenticated or optionally authenticated public endpoints
 * No 401 refresh interceptor since these are public routes
 */
export const mediaPublicApi = axios.create({
  baseURL: '/media',
  headers: {
    'Content-Type': 'application/json',
  },
});

/**
 * Generate or retrieve session ID for anonymous tracking
 * Stored in localStorage for upvote/comment tracking
 */
export function getOrCreateSessionId(): string {
  const STORAGE_KEY = 'media_session_id';
  let sessionId = localStorage.getItem(STORAGE_KEY);

  if (!sessionId) {
    // Generate UUID v4 using crypto API
    sessionId = crypto.randomUUID();
    localStorage.setItem(STORAGE_KEY, sessionId);
  }

  return sessionId;
}

/**
 * Attach session ID to request headers
 * Used for upvote/comment tracking without auth
 */
mediaPublicApi.interceptors.request.use(
  (config) => {
    const sessionId = getOrCreateSessionId();
    config.headers['X-Session-ID'] = sessionId;

    // Optionally attach Bearer token if user is logged in
    const callbacks = getAuthCallbacks();
    const accessToken = callbacks.getAccessToken();
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    }

    return config;
  },
  (error) => Promise.reject(error)
);
