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

import { normalizeSearchPipelineConfig, type SearchPipelineConfig, type SearchPreset } from '@/types';
import { resolveSearchTemplateId } from '@/lib/searchTemplateResolution';

const defaultConfig: SearchPipelineConfig = {
  keywordSearchEnabled: true,
  imageSearchEnabled: true,
  keywordCombinations: [],
  includeAiKeyword: true,
};

describe('resolveSearchTemplateId', () => {
  it('resolves to a saved preset when the current config matches it exactly', () => {
    const presetConfig: SearchPipelineConfig = {
      keywordSearchEnabled: true,
      imageSearchEnabled: true,
      keywordCombinations: [
        { fields: ['standardized_name'], label: '标准化名称' },
        { fields: ['standardized_name', 'brand'], label: '标准化名称+品牌' },
      ],
      includeAiKeyword: false,
    };

    const presets: SearchPreset[] = [{
      id: 'preset-2',
      user_id: 'user-1',
      name: '预设 2',
      config: presetConfig,
      is_default: false,
      created_at: '2026-04-20T08:00:00.000Z',
      updated_at: '2026-04-20T08:00:00.000Z',
    }];

    expect(resolveSearchTemplateId(presetConfig, presets)).toBe('preset-2');
  });

  it('keeps an explicitly selected builtin template when the config still matches it', () => {
    const presets: SearchPreset[] = [{
      id: 'preset-default-copy',
      user_id: 'user-1',
      name: '默认副本',
      config: defaultConfig,
      is_default: false,
      created_at: '2026-04-20T08:00:00.000Z',
      updated_at: '2026-04-20T08:00:00.000Z',
    }];

    expect(resolveSearchTemplateId(defaultConfig, presets, 'default')).toBe('default');
  });

  it('falls back to custom for ad-hoc keyword combinations', () => {
    const customConfig: SearchPipelineConfig = {
      keywordSearchEnabled: true,
      imageSearchEnabled: false,
      keywordCombinations: [
        { fields: ['primary_search_term', 'notes'], label: '主搜索词+备注' },
      ],
      includeAiKeyword: true,
    };

    expect(resolveSearchTemplateId(customConfig, [])).toBe('custom');
  });

  it('normalizes legacy field presets before matching builtin templates', () => {
    const legacyConfig = normalizeSearchPipelineConfig({
      keywordSearchEnabled: true,
      imageSearchEnabled: true,
      keywordCombinations: [
        { fields: ['name', 'spec', 'parameters'], label: '名称+规格+参数词' },
      ],
      includeAiKeyword: true,
    });

    expect(legacyConfig.keywordCombinations).toEqual([
      { fields: ['standardized_name', 'standardized_spec'], label: '标准化名称+标准化规格' },
    ]);
    expect(resolveSearchTemplateId(legacyConfig, [])).toBe('name_spec');
  });
});