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

import {
  buildPluginListRouteQuery,
  buildPluginToolListRouteQuery,
  mergePluginListRouteQuery,
  mergePluginToolListRouteQuery,
  parsePluginListRouteState,
  parsePluginToolListRouteState,
} from './plugin-route-state';

describe('plugin route state', () => {
  it('restores plugin list page, category and keyword', () => {
    expect(
      parsePluginListRouteState({
        categoryId: '7',
        keyword: '天气',
        pageNumber: '3',
        pageSize: '24',
      }),
    ).toEqual({
      categoryId: '7',
      keyword: '天气',
      pageNumber: 3,
      pageSize: 24,
    });
  });

  it('serializes plugin list state into canonical list query', () => {
    const state = {
      categoryId: '7',
      keyword: '天气',
      pageNumber: 3,
      pageSize: 24,
    };
    expect(buildPluginListRouteQuery(state)).toEqual({
      categoryId: '7',
      keyword: '天气',
      pageNumber: '3',
      pageSize: '24',
    });
  });

  it('falls back safely for invalid plugin and tool pagination', () => {
    expect(
      parsePluginListRouteState({
        pageNumber: '-1',
        pageSize: '999',
      }),
    ).toEqual({
      categoryId: '0',
      keyword: '',
      pageNumber: 1,
      pageSize: 12,
    });
    expect(
      parsePluginToolListRouteState({
        pageNumber: '0',
        pageSize: '999',
      }),
    ).toEqual({
      keyword: '',
      pageNumber: 1,
      pageSize: 10,
    });
  });

  it('preserves unrelated route query while updating list state', () => {
    expect(
      mergePluginListRouteQuery(
        {
          devLogin: 'admin',
          keyword: '旧关键字',
          pageNumber: '4',
        },
        {
          categoryId: '0',
          keyword: '',
          pageNumber: 1,
          pageSize: 12,
        },
      ),
    ).toEqual({ devLogin: 'admin' });
  });

  it('keeps plugin return context when tool list state changes', () => {
    expect(
      mergePluginToolListRouteQuery(
        {
          id: '88',
          returnTo: '/ai/plugin?categoryId=7&pageNumber=3',
          keyword: '旧工具',
        },
        {
          keyword: '查询工具',
          pageNumber: 2,
          pageSize: 20,
        },
      ),
    ).toEqual({
      id: '88',
      keyword: '查询工具',
      pageNumber: '2',
      pageSize: '20',
      returnTo: '/ai/plugin?categoryId=7&pageNumber=3',
    });
  });

  it('serializes plugin tool list state with common query keys', () => {
    expect(
      buildPluginToolListRouteQuery({
        keyword: '查询工具',
        pageNumber: 2,
        pageSize: 20,
      }),
    ).toEqual({
      keyword: '查询工具',
      pageNumber: '2',
      pageSize: '20',
    });
  });
});
