import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { gameApp } from '../dist/server.js';
import { credentials } from '../dist/shared/auth.js';
import { DashboardStore } from '../dist/shared/store.js';

export const password = 'only-for-tests-not-a-real-password';
export async function fixture() {
    const directory = await mkdtemp(join(tmpdir(), 'redweb-game-tutorial-'));
    const database = join(directory, 'test.sqlite');
    const store = new DashboardStore(database);
    const secret = await credentials(password);
    for (const account of ['alice', 'bob', 'carol']) store.provision(account, secret);
    store.close();
    const app = gameApp({ database, port: 0, signals: false });
    await app.run();
    const origin = `http://localhost:${app.server.address().port}`;
    return { app, origin, database, async close() {
        await app.shutdown();
        // Only this fixture's freshly allocated, exact directory is removed.
        await rm(directory, { recursive: true, force: true });
    } };
}
export function post(origin, path, values, cookie, suppliedOrigin = origin) {
    return fetch(`${origin}${path}`, { method: 'POST', redirect: 'manual',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: suppliedOrigin, ...(cookie ? { Cookie: cookie } : {}) },
        body: new URLSearchParams(values),
    });
}
export async function login(origin, account) {
    const response = await post(origin, '/login', { account, password });
    assert.equal(response.status, 303);
    const cookie = response.headers.get('set-cookie');
    assert.match(cookie, /HttpOnly; SameSite=Strict/);
    return cookie.split(';')[0];
}
