import { test, expect } from '@playwright/test';
import { ae_app_local_data_defaults } from './_helpers/ae_defaults';

test.describe('V3 API Header Integrity (modernized)', () => {
	test.setTimeout(10000);

	test.beforeEach(async ({ page }) => {
		page.on('pageerror', (err) => console.error(`BROWSER ERROR: ${err.message}`));
		page.on('console', (msg) => {
			if (msg.type() === 'error' || msg.type() === 'warning') {
				console.error(`BROWSER [${msg.type().toUpperCase()}]: ${msg.text()}`);
			}
		});

		// Mock local /v3/ endpoints used by the app to make the test deterministic.
		await page.route('**/v3/**', async (route) => {
			const req = route.request();
			const url = req.url();

			if (url.includes('site_domain/search')) {
				return route.fulfill({
					status: 200,
					contentType: 'application/json',
					body: JSON.stringify({ data: [{ id: 'test-site', account_id: 'test-account-id', site_id: 'test-site-id', cfg_json: {} }] })
				});
			}

			if (url.includes('/v3/lookup/country/list')) {
				return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [] }) });
			}

			if (url.includes('/v3/crud/user/search')) {
				return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [] }) });
			}

			return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [] }) });
		});
	});

	test('Verify lookup requests use account-scoped headers (no bypass)', async ({ page }) => {
		await page.addInitScript((defaults) => {
			const testData = { ...defaults, account_id: 'test-account-id', manager_access: true };
			window.localStorage.setItem('ae_loc', JSON.stringify(testData));
		}, ae_app_local_data_defaults);

		const requestPromise = page.waitForRequest((request) => request.url().includes('/v3/lookup/country/list'));

		await page.goto('/core/lookups');

		const request = await requestPromise;
		const headers = request.headers();

		// Current lookup policy is account-scoped for these routes.
		// The bypass header should not be sent here.
		expect(headers['x-no-account-id']).toBeUndefined();
		expect(headers['x-account-id']).toBe('test-account-id');
		expect(headers['x-aether-api-key']).toBeDefined();
	});

	test('Verify Account ID Scavenging from localStorage on CRUD requests', async ({ page }) => {
		const test_account_id = '_XY7DXtc9MY'; // Per README test data

		await page.addInitScript(({ defaults, id }) => {
			const testData = { ...defaults, account_id: id, manager_access: true };
			window.localStorage.setItem('ae_loc', JSON.stringify(testData));
		}, { defaults: ae_app_local_data_defaults, id: test_account_id });

		const requestPromise = page.waitForRequest((request) => request.url().includes('/v3/crud/user/search'));

		await page.goto('/core/users');

		const request = await requestPromise;
		const headers = request.headers();

		expect(headers['x-account-id']).toBe(test_account_id);
	});
});
