const getCookieValue = (
	name: string | string[]
): null | string | { accesstoken: string; timestamp: number } => {
	if (Array.isArray(name)) {
		// it will be array only in App.tsx nowhere else so the old logic should still work fine
		const cookie = new RegExp(`${name[0]}=([^;]+)`);
		let value = null;
		if (typeof document !== 'undefined') {
			value = cookie.exec(document.cookie);
		}

		if (value != null) {
			const cookieParts = decodeURIComponent(value[1]).split('|'); // Split on '|'
			return { accesstoken: cookieParts[0], timestamp: parseInt(cookieParts[1], 10) };
		}
	} else {
		const cookie = new RegExp(`${name}=([^;]+)`);
		let value = null;
		if (typeof document !== 'undefined') {
			value = cookie.exec(document.cookie);
		}

		if (value != null) {
			const cookieParts = decodeURIComponent(value[1]).split('|'); // Split on '|'

			if (cookieParts.length > 1) {
				const storedValue = cookieParts[0]; // Access token
				const timestamp = parseInt(cookieParts[1], 10); // Access timestamp

				// Check if the timestamp is valid
				if (!isNaN(timestamp) && Date.now() <= timestamp) {
					return storedValue; // Return the access token if valid
				}
			}
		}
	}

	return null; // Return null if the cookie doesn't exist.
};

export default getCookieValue;
