import { describe, expect, it } from 'vitest';

import { getWebViewNavigationAction } from '../webview-navigation';

describe('getWebViewNavigationAction', () => {
  const productionUrl = 'https://www.learnitive.com';

  it('allows navigation within the configured HTTPS origin', () => {
    expect(
      getWebViewNavigationAction(
        'https://www.learnitive.com/notes?view=all#today',
        productionUrl,
      ),
    ).toBe('allow');
    expect(
      getWebViewNavigationAction(
        'https://www.learnitive.com:443/notes',
        productionUrl,
      ),
    ).toBe('allow');
  });

  it('externalizes an HTTP downgrade on the configured host', () => {
    expect(
      getWebViewNavigationAction('http://app.learnitive.com/notes', productionUrl),
    ).toBe('external');
  });

  it('externalizes a port mismatch on the configured host', () => {
    expect(
      getWebViewNavigationAction(
        'https://www.learnitive.com:8443/notes',
        productionUrl,
      ),
    ).toBe('external');
  });

  it('externalizes other HTTPS origins', () => {
    expect(
      getWebViewNavigationAction('https://example.com/notes', productionUrl),
    ).toBe('external');
  });

  it.each([
    'https://evil.example\\@app.learnitive.com/notes',
    'https://user@app.learnitive.com/notes',
    'https://www.learnitive.com:65536/notes',
  ])('rejects ambiguous or invalid authorities: %s', (requestUrl) => {
    expect(getWebViewNavigationAction(requestUrl, productionUrl)).toBe(
      'reject',
    );
  });

  it('allows an explicitly configured HTTP LAN origin', () => {
    const lanUrl = 'http://192.168.1.20:5173';

    expect(
      getWebViewNavigationAction('http://192.168.1.20:5173/notes', lanUrl),
    ).toBe('allow');
    expect(
      getWebViewNavigationAction('https://192.168.1.20:5173/notes', lanUrl),
    ).toBe('external');
  });

  it('only allows about:blank and rejects URLs without a trusted origin', () => {
    expect(getWebViewNavigationAction('about:blank', productionUrl)).toBe(
      'allow',
    );
    expect(getWebViewNavigationAction('about:srcdoc', productionUrl)).toBe(
      'reject',
    );
    expect(
      getWebViewNavigationAction('javascript:alert(1)', productionUrl),
    ).toBe('reject');
  });
});
