import axios from 'axios'
import Echo from 'laravel-echo'
import Pusher from 'pusher-js'

window.axios = axios
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
if (csrfToken) {
	window.axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken
}

window.Pusher = Pusher

let echoInstance = null

export function getEcho() {
	if (echoInstance !== null) {
		return echoInstance || null
	}

	const key = import.meta.env.VITE_REVERB_APP_KEY
	if (!key) {
		echoInstance = false
		return null
	}

	const scheme = import.meta.env.VITE_REVERB_SCHEME || window.location.protocol.replace(':', '') || 'https'
	const forceTLS = scheme === 'https'

	echoInstance = new Echo({
		broadcaster: 'reverb',
		key,
		wsHost: import.meta.env.VITE_REVERB_HOST || window.location.hostname,
		wsPort: Number(import.meta.env.VITE_REVERB_PORT || (forceTLS ? 443 : 80)),
		wssPort: Number(import.meta.env.VITE_REVERB_PORT || 443),
		forceTLS,
		enabledTransports: ['ws', 'wss'],
		authEndpoint: '/broadcasting/auth',
		auth: {
			headers: {
				'X-CSRF-TOKEN': csrfToken || '',
				Accept: 'application/json',
			},
		},
	})

	window.Echo = echoInstance

	return echoInstance
}
