import { tokenValidation } from '../store';

export function setTokenCookie(token) {
	document.cookie = `token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;

	const expiration = new Date(Date.now() + 30 * 60 * 1000);
	document.cookie = `token=${token}-time=${expiration.toUTCString()}; path=/; expires=${expiration.toUTCString()}`;
}

export function getToken() {
	const tokenCookie = document.cookie.split('; ').find((row) => row.startsWith('token='));

	if (tokenCookie == null) return null;

	const [tokenPart] = tokenCookie.split('-time=');
	return tokenPart.replace('token=', '');
}

export function checkTokenExpiry() {
	const tokenCookie = document.cookie.split('; ').find((row) => row.startsWith('token='));
	if (tokenCookie == null) {
		tokenValidation.set(true);
		return;
	}

	const [tokenPart, timePart] = tokenCookie.split('-time=');

	if (timePart == null) {
		tokenValidation.set(true);
		return;
	}

	const expirationTime = new Date(timePart);
	const now = new Date();
	const timeDiff = expirationTime - now;

	if (timeDiff <= 0) {
		tokenValidation.set(true);
	} else if (timeDiff <= 5 * 60 * 1000) {
		const myHeaders = new Headers();
		myHeaders.append('Content-Type', 'application/json');

		const raw = JSON.stringify({
			email: localStorage.getItem('email')
		});
		const requestOptions = {
			method: 'POST',
			headers: myHeaders,
			body: raw,
			redirect: 'follow'
		};

		fetch('http://localhost:3005/api/refresh-token', requestOptions)
			.then((response) => response.json())
			.then((result) => setTokenCookie(result.data.token));
	}
	tokenValidation.set(false);
}
