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

import {
  buildAbsoluteAppRouteUrl,
  readScopedRouteQueryParam,
} from './share-route-context';

describe('share route context', () => {
  it('reads a knowledge share key from the active hash route', () => {
    expect(
      readScopedRouteQueryParam(
        '/share/knowledge',
        'shareKey',
        'https://example.test/flow/#/share/knowledge?shareKey=knowledge-key',
      ),
    ).toBe('knowledge-key');
  });

  it('reads a knowledge share key from a history route', () => {
    expect(
      readScopedRouteQueryParam(
        '/share/knowledge',
        'shareKey',
        'https://example.test/flow/share/knowledge?shareKey=knowledge-key',
      ),
    ).toBe('knowledge-key');
  });

  it('prefers the active hash route over an outer query', () => {
    expect(
      readScopedRouteQueryParam(
        '/share/knowledge',
        'shareKey',
        'https://example.test/flow/share/knowledge?shareKey=stale-key#/ai/workflow',
      ),
    ).toBeNull();
  });

  it('keeps the hash route when building an absolute share URL', () => {
    expect(
      buildAbsoluteAppRouteUrl(
        '/flow/#/share/knowledge?shareKey=knowledge-key',
        'https://example.test',
      ),
    ).toBe(
      'https://example.test/flow/#/share/knowledge?shareKey=knowledge-key',
    );
  });

  it('keeps the runtime base path for a hash-only router href', () => {
    const previousPath = `${window.location.pathname}${window.location.search}`;
    window.history.replaceState({}, '', '/flow/');
    try {
      expect(
        buildAbsoluteAppRouteUrl(
          '#/share/knowledge?shareKey=knowledge-key',
          'https://example.test',
        ),
      ).toBe(
        'https://example.test/flow/#/share/knowledge?shareKey=knowledge-key',
      );
    } finally {
      window.history.replaceState({}, '', previousPath);
    }
  });
});
