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

test('loader injects dependency script urls', async ({ page }) => {
    page.on('console', msg => console.log('BROWSER LOG:', msg.text()));

    await page.setContent(`
      <!DOCTYPE html>
      <html>
      <head>
        <script src="http://127.0.0.1:8084/dist/loader.js"></script>
      </head>
      <body>
        <div id="status">loading</div>
      </body>
      </html>
    `, { waitUntil: 'commit' });

    await page.waitForFunction(() => typeof window.__apigo_load === 'function');
    await page.waitForFunction(() => document.readyState !== 'loading');

    const urls = await page.evaluate(() => {
        const captured = [];
        const originalAppend = document.head.appendChild.bind(document.head);

        document.head.appendChild = node => {
            if (node && node.tagName === 'SCRIPT' && node.src) {
                captured.push(node.src);
            }
            return node;
        };

        __apigo_load('state', 'bootstrap', 'base');

        document.head.appendChild = originalAppend;
        return captured;
    });

    expect(urls).toEqual([
        'https://cdn.jsdelivr.net/npm/@apigo.cc/state@1.0.23/dist/state.js',
        'https://cdn.jsdelivr.net/npm/@apigo.cc/bootstrap@1.0.9/dist/bootstrap.js',
        'https://cdn.jsdelivr.net/npm/@apigo.cc/base@1.0.23/dist/base.js'
    ]);
});
