import { test, expect } from '@playwright/test';

test('API keeps declarative preset request fields', async ({ page }) => {
    let capturedBody = null;
    await page.route('**/echo', async route => {
        capturedBody = route.request().postData();
        await route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ ok: true })
        });
    });

    await page.goto('/test/api_test.html');
    await page.waitForFunction(() => typeof globalThis.presetApi?.do === 'function' && !!globalThis.presetApi?.request);

    const requestInfo = await page.evaluate(() => ({
        url: presetApi.request?.url,
        method: presetApi.request?.method,
        secret: presetApi.request?.data?.secret
    }));

    expect(requestInfo).toEqual({
        url: '/echo',
        method: 'POST',
        secret: 'playwright-secret'
    });

    const ok = await page.evaluate(async () => {
        const resp = await presetApi.do({ noui: true });
        return resp.ok;
    });

    expect(ok).toBe(true);
    expect(capturedBody).toBe(JSON.stringify({ secret: 'playwright-secret' }));
});
