import { toast } from 'sonner'
import { AUDITLOG_API_URL } from '@/shared/config/app.config'
import { createHttpClient, type TokenPair } from '../http/http-client-factory'
import { getRefreshToken } from '@/shared/utils/refreshTokenHandler'

async function refreshFn(refreshToken: string): Promise<TokenPair> {
	const res = await getRefreshToken(refreshToken)
	return {
		accessToken: res.data.token,
		refreshToken: res.data.refreshToken,
	}
}

export const auditHttp = createHttpClient({
	baseURL: AUDITLOG_API_URL,
	cookieKeys: {
		access: 'auth-token',
		refresh: 'refresh-token',
		user: 'auth-user',
	},
	refreshFn,
	skipRefreshPaths: ['/auth/login', '/auth/refresh', '/auth/me'],
	onAuthFailure: () => {
		toast.error('Session expired', {
			description: 'Please log in again.',
			duration: 4000,
		})

		setTimeout(() => {
			window.location.href = '/'
		}, 1200)
	},
})
