// @vitest-environment jsdom
import { describe, it, expect, beforeEach } from 'vitest';
import { get, set, remove } from './cookies.js';

// Strip every cookie before each test so they don't bleed between cases.
function clearAllCookies() {
    for (const cookie of document.cookie.split('; ')) {
        const eq = cookie.indexOf('=');
        const name = eq > 0 ? cookie.slice(0, eq) : cookie;
        if (name) {
            document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
        }
    }
}

beforeEach(() => {
    clearAllCookies();
});

describe('get()', () => {
    it('returns undefined when the cookie is not set', () => {
        expect(get('nope')).toBeUndefined();
    });

    it('reads back a value that was just set', () => {
        document.cookie = 'currency=GBP';
        expect(get('currency')).toBe('GBP');
    });

    it('decodes URL-encoded values', () => {
        document.cookie = `greeting=${encodeURIComponent('hello world')}`;
        expect(get('greeting')).toBe('hello world');
    });

    it('returns undefined for the wrong key when other cookies exist', () => {
        document.cookie = 'currency=GBP';
        document.cookie = 'session=abc';
        expect(get('missing')).toBeUndefined();
    });
});

describe('set()', () => {
    it('round-trips a simple key/value via get()', () => {
        set('currency', 'EUR');
        expect(get('currency')).toBe('EUR');
    });

    it('URL-encodes values with reserved characters', () => {
        set('redirect', '/foo?bar=1&baz=2');
        expect(get('redirect')).toBe('/foo?bar=1&baz=2');
    });

    it('writes an expires attribute when expires is a number of days', () => {
        // jsdom keeps non-expired cookies; we can't easily inspect attributes,
        // so just confirm the cookie is still readable.
        set('currency', 'USD', { expires: 30, path: '/' });
        expect(get('currency')).toBe('USD');
    });

    it('writes an expires attribute when expires is a Date', () => {
        const future = new Date(Date.now() + 86400000);
        set('temp', 'ok', { expires: future });
        expect(get('temp')).toBe('ok');
    });
});

describe('remove()', () => {
    it('clears a previously-set cookie', () => {
        set('currency', 'GBP', { path: '/' });
        expect(get('currency')).toBe('GBP');

        remove('currency', { path: '/' });
        expect(get('currency')).toBeUndefined();
    });
});
