import {isDesktop} from '@/lib/configs';

export function getCookie(name: string): string | null {
    const nameEQ: string = `${name}=`;
    const allCookies: string[] = document.cookie.split(';');
    for (let i: number = 0; i < allCookies.length; i++) {
        let cookie: string = allCookies[i];
        while (cookie.charAt(0) === ' ') cookie = cookie.substring(1, cookie.length);
        if (cookie.indexOf(nameEQ) === 0) return cookie.substring(nameEQ.length, cookie.length);
    }
    return null;
}

export function setCookie(name: string, value: string, days: number): void {
    const date: Date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires: string = `expires=${date.toUTCString()}`;
    let domain: string = '';
    if (!isDesktop && !/localhost|127\.0\.0\.1/.test(window.location.hostname)) {
        domain = `domain=${window.location.hostname};`;
    }
    const secure: string = isDesktop ? '' : 'Secure;';
    const sameSite: string = 'SameSite=Strict;';
    document.cookie = `${name}=${value}; ${expires}; ${domain} path=/; ${secure} ${sameSite}`;
}

export function removeCookie(name: string): void {
    let domain: string = '';
    if (!isDesktop && !/localhost|127\.0\.0\.1/.test(window.location.hostname)) {
        domain = `domain=${window.location.hostname};`;
    }
    const secure: string = isDesktop ? '' : 'Secure;';
    const sameSite: string = 'SameSite=Strict;';
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; ${domain} path=/; ${secure} ${sameSite}`;
}
