import { describe, it, expect, beforeEach, vi } from 'vitest';
// polyfill btoa for Node test environment
function btoaPolyfill(bin) {
    return Buffer.from(bin, 'binary').toString('base64');
}
describe('s2readRuntime', () => {
    beforeEach(() => {
        ;
        globalThis.btoa = globalThis.btoa ?? btoaPolyfill;
    });
    it('in input=sql mode, sends v:0 base64url(JSON) token', async () => {
        const fetchMock = vi.fn(async (_url, init) => {
            const body = JSON.parse(init.body);
            return new Response(JSON.stringify([{ ok: true, payload: body.payload }]), {
                status: 200,
                headers: { 'content-type': 'application/json' }
            });
        });
        globalThis.fetch = fetchMock;
        const { s2readRuntime } = await import('./runtime.js');
        // call once; debounce 0 ensures immediate run
        const rowsRef = s2readRuntime({ id: 1 }, ['select 1 as x'], [true], { input: 'sql', endpoint: '/api/read', debounceMs: 0 });
        // wait microtasks
        await new Promise((r) => setTimeout(r, 0));
        expect(fetchMock).toHaveBeenCalledTimes(1);
        const sent = JSON.parse(fetchMock.mock.calls[0][1].body);
        const payload = String(sent.payload);
        // decode base64url JSON
        const json = Buffer.from(payload, 'base64url').toString('utf8');
        const obj = JSON.parse(json);
        expect(obj.v).toBe(0);
        expect(obj.sql).toBe('select 1 as x');
        expect(obj.isSelect).toBe(true);
        expect(Array.isArray(rowsRef.value)).toBe(true);
        expect(rowsRef.value[0]?.ok).toBe(true);
    });
    it('in input=token mode, sends token as-is', async () => {
        const fetchMock = vi.fn(async (_url, init) => {
            const body = JSON.parse(init.body);
            return new Response(JSON.stringify([{ payload: body.payload }]), {
                status: 200,
                headers: { 'content-type': 'application/json' }
            });
        });
        globalThis.fetch = fetchMock;
        const { s2readRuntime } = await import('./runtime.js');
        const tok = 'AdiuFxoqtzgfgTS0y0u1zw...';
        s2readRuntime({}, [tok], [true], { input: 'token', endpoint: '/api/read', debounceMs: 0 });
        await new Promise((r) => setTimeout(r, 0));
        const sent = JSON.parse(fetchMock.mock.calls[0][1].body);
        expect(sent.payload).toBe(tok);
    });
});
