// @vitest-environment happy-dom

import { mount } from '@vue/test-utils';
import { defineComponent, h } from 'vue';

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

import AgentSkillSelectorDialog from './AgentSkillSelectorDialog.vue';

const dialogStub = defineComponent({
  name: 'ElDialog',
  props: {
    modelValue: Boolean,
    title: { default: '', type: String },
  },
  emits: ['update:modelValue'],
  setup(props, { slots }) {
    return () =>
      props.modelValue
        ? h('section', [
            h('h2', props.title),
            slots.default?.(),
            slots.footer?.(),
          ])
        : null;
  },
});

const options = [
  {
    label: '合同审查助手',
    value: 'skill-1',
    raw: {
      description: '识别风险条款并生成审查意见',
      textResourceCount: 2,
      toolCount: 1,
      visibilityScope: 'DEPARTMENT',
    },
  },
  {
    label: '季度经营分析',
    value: 'skill-2',
    raw: {
      description: '汇总经营数据',
      textResourceCount: 1,
      toolCount: 0,
      visibilityScope: 'PRIVATE',
    },
  },
];

function mountDialog(props: Record<string, unknown> = {}) {
  return mount(AgentSkillSelectorDialog, {
    global: {
      directives: { loading: {} },
      stubs: { ElDialog: dialogStub },
    },
    props: {
      modelValue: true,
      options,
      ...props,
    } as never,
  });
}

describe('agent skill selector dialog', () => {
  it('fuzzy searches multiple terms and supports keyboard selection', async () => {
    const wrapper = mountDialog();

    await wrapper.get('input[aria-label="搜索技能"]').setValue('合同 意见');
    expect(wrapper.text()).toContain('合同审查助手');
    expect(wrapper.text()).not.toContain('季度经营分析');

    await wrapper.get('[role="option"]').trigger('keydown.enter');
    const addButton = wrapper
      .findAll('button')
      .find((button) => button.text().trim() === '添加');
    await addButton?.trigger('click');

    expect(wrapper.emitted('add')?.[0]?.[0]).toEqual([options[0]]);
  });

  it('disables new selections after reaching the twenty-skill limit', () => {
    const wrapper = mountDialog({
      boundSkillIds: Array.from({ length: 20 }, (_, index) => `bound-${index}`),
    });

    expect(wrapper.text()).toContain('已达到绑定上限');
    expect(wrapper.get('[role="option"]').attributes('aria-disabled')).toBe(
      'true',
    );
  });

  it('shows a retry action when options fail to load', async () => {
    const wrapper = mountDialog({ error: '加载失败' });
    const retryButton = wrapper
      .findAll('button')
      .find((button) => button.text().trim() === '重新加载');

    await retryButton?.trigger('click');

    expect(wrapper.text()).toContain('技能列表加载失败');
    expect(wrapper.emitted('retry')).toHaveLength(1);
  });
});
