<script>
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	let autorizado = false;
	import { browser } from '$app/environment';
	import { tokenValidation } from '$lib/utils/store';
	let flag = null;
	let token = null;
	let company = null;

	if (browser) {
		flag = localStorage.getItem('flag');
		token = localStorage.getItem('token');
		company = Number(localStorage.getItem('company'));
	}

	function fetchUsers() {
		const token = localStorage.getItem('token');
		const company = parseInt(localStorage.getItem('company'), 10);

		fetch('https://dev2.mixtech.dev.br/user/get', {
			method: 'POST',
			headers: {
				Authorization: `Bearer ${token}`,
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({ company_id: company })
		})
			.then((response) => {
				if (!response.ok) {
					console.error(`Erro HTTP: ${response.status}`);
					if (response.status === 401) {
						tokenValidation.set(true);
					}
				}
			})
			.catch((error) => {
				console.error('Erro de rede ou requisição:', error);
			});
	}

	onMount(async () => {
		if (flag !== 'admin' && flag !== 'waiter' && flag !== 'kitchen' && flag !== 'cashier') {
			goto('/login');
		} else {
			autorizado = true;
		}
		setInterval(() => {
			fetchUsers();
		}, 5000);
	});
</script>

{#if autorizado}
	<slot />
{/if}
