import { createMemoryHistory, createRouter } from 'vue-router';

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

import {
  readListReturnTo,
  resolveListReturnPath,
  withListReturnTo,
} from './list-return-context';

function createTestRouter() {
  return createRouter({
    history: createMemoryHistory(),
    routes: [
      { component: {}, path: '/items' },
      { component: {}, path: '/other' },
    ],
  });
}

describe('list return context', () => {
  it('round trips an exact internal list URL', () => {
    const router = createTestRouter();
    const query = withListReturnTo('/items?pageNumber=4&keyword=月报', {
      id: '7',
    });

    expect(readListReturnTo(query as any)).toBe(
      '/items?pageNumber=4&keyword=月报',
    );
    expect(
      resolveListReturnPath(router, query as any, ['/items'], '/items'),
    ).toBe('/items?pageNumber=4&keyword=月报');
  });

  it.each([
    'https://example.com/items?pageNumber=4',
    '//example.com/items?pageNumber=4',
    '/other?pageNumber=4',
    '/missing?pageNumber=4',
    '/items#unsafe',
    String.raw`/items\unsafe`,
    `/items?value=${'x'.repeat(4096)}`,
  ])('rejects an unsafe or unrelated return target: %s', (returnTo) => {
    expect(
      resolveListReturnPath(
        createTestRouter(),
        { returnTo },
        ['/items'],
        '/items',
      ),
    ).toBe('/items');
  });
});
