import type { Cookies } from '@sveltejs/kit';

export class CookieAuthentication {
    private readonly cookieValue: string;
    private readonly cookieValueArray: string[];
    public static cookieName = 'auth';
    public static adminAuthRole = 'admin';

    constructor(private readonly cookies: Cookies) {
        this.cookieValue = this.cookies.get(CookieAuthentication.cookieName) ?? '';
        this.cookieValueArray = this.cookieValue.split(',');
    }

    public get isAuthdAsAdmin(): boolean {
        let isAuthdAsAdmin = false;

        if (this.cookieValueArray.includes(CookieAuthentication.adminAuthRole)) {
            isAuthdAsAdmin = true;
        }

        return isAuthdAsAdmin;
    }

    public logout() {
        if (!this.isAuthdAsAdmin) return;

        this.cookies.delete(CookieAuthentication.cookieName, { path: '/' });
    }

    public setAdminAuthentication(isAuthd: boolean) {
        let value = this.cookieValue;

        if (isAuthd) {
            value = Array.from(new Set([...this.cookieValueArray, CookieAuthentication.adminAuthRole])).join(',');
        } else {
            value = this.cookieValueArray.filter((i) => i !== CookieAuthentication.adminAuthRole).join(',');
        }

        this.cookies.set(CookieAuthentication.cookieName, value, { path: '/' });
    }
}
