import { runInNewContext } from 'node:vm';

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

import {
  buildBasePathRedirectScript,
  resolveBasePathRedirect,
} from './vite-base-path-redirect';

describe('vite base path redirect', () => {
  it.each([
    ['/', '/flow/'],
    ['/flow', '/flow/'],
    ['/flow?from=bookmark', '/flow/?from=bookmark'],
  ])('redirects %s to %s', (requestUrl, expected) => {
    expect(resolveBasePathRedirect(requestUrl, '/flow/')).toBe(expected);
  });

  it.each(['/flow/', '/flow/api/v1/user/info', '/other'])(
    'keeps %s unchanged',
    (requestUrl) => {
      expect(resolveBasePathRedirect(requestUrl, '/flow/')).toBeNull();
    },
  );

  it('does not redirect when the application is deployed at root', () => {
    expect(resolveBasePathRedirect('/', '/')).toBeNull();
  });

  it.each([
    ['/', '', '', '/flow/'],
    [
      '/flow',
      '?from=bookmark',
      '#/dashboard',
      '/flow/?from=bookmark#/dashboard',
    ],
    ['/flow/', '', '#/dashboard', null],
  ])(
    'normalizes browser entry %s before the router starts',
    (pathname, search, hash, expected) => {
      const replacements: string[] = [];
      runInNewContext(buildBasePathRedirectScript('/flow/'), {
        window: {
          location: {
            hash,
            pathname,
            replace: (target: string) => replacements.push(target),
            search,
          },
        },
      });
      expect(replacements[0] ?? null).toBe(expected);
    },
  );
});
