import React, { useEffect } from 'react';
import { useAuth } from '@clerk/clerk-react';
import { apiClient } from '../api/client';

interface Props {
  children: React.ReactNode;
}

export const ApiInterceptor: React.FC<Props> = ({ children }) => {
  const { getToken } = useAuth();

  useEffect(() => {
    const interceptorId = apiClient.interceptors.request.use(
      async (config) => {
        const token = await getToken();
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    return () => {
      apiClient.interceptors.request.eject(interceptorId);
    };
  }, [getToken]);

  return <>{children}</>;
};
