import axios from 'axios'
import { TokenService } from '../services/token.service'
import { QuickBooksService } from '../services/quickbooks.service'

export const createQuickbooksAPI = (tokenService: TokenService) => {
    const baseURL = `${process.env.QUICKBOOKS_API_URL}/company/${process.env.QUICKBOOKS_REALM_ID}/`
	const quickbooksAPI = axios.create({
		baseURL,
		params: {
			minorversion: 75,
		},
	})

	// Interceptor to add the token dynamically before every request
	quickbooksAPI.interceptors.request.use(
		async (config) => {
			// Get the access token from TokenService before each request
			const accessToken = (await tokenService.getLatestToken('quickbooks'))?.accessToken

			// Check if token exists
			if (!accessToken) {
				throw new Error('Access token not found')
			}

			// Add the Authorization header
			config.headers['Authorization'] = `Bearer ${accessToken}`
			return config // Continue with the request
		},
		(error) => {
			return Promise.reject(error) // Handle the error
		},
	)

	// Response interceptor to handle 401 errors (unauthorized)
	quickbooksAPI.interceptors.response.use(
		(response) => {
			return response // Return successful responses as-is
		},
		async (error) => {
			const originalRequest = error.config

			// If the error is 401 (Unauthorized) and we haven't already tried to refresh
			if (error.response?.status === 401 && !originalRequest._retry) {
				originalRequest._retry = true // Mark that we've tried to refresh for this request

				try {
					// Create a temporary instance of QuickBooksService to refresh the token
					const quickBooksService = new QuickBooksService(tokenService)
					
					// Refresh the token
					const newAccessToken = await quickBooksService.getAccessToken({ type: 'refresh' })
					
					// Update the Authorization header with the new token
					originalRequest.headers['Authorization'] = `Bearer ${newAccessToken}`
					
					// Retry the original request with the new token
					return quickbooksAPI(originalRequest)
				} catch (refreshError) {
					console.error('Failed to refresh token:', refreshError)
					return Promise.reject(refreshError)
				}
			}
			
			// For other errors, just reject the promise
			return Promise.reject(error)
		}
	)

	return quickbooksAPI
}
