/* @vitest-environment happy-dom */

import { mount } from '@vue/test-utils';
import Antd from 'ant-design-vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import CodeAssistModal from '../CodeAssistModal.vue';

const modalState = vi.hoisted(() => ({
  closeModal: vi.fn(),
  init: undefined as any,
}));

vi.mock('@jnpf/ui/modal', async () => {
  const { getCurrentInstance, onMounted } = await import('vue');
  return {
    BasicModal: {
      emits: ['ok', 'register'],
      name: 'BasicModal',
      props: ['okButtonProps', 'okText', 'title'],
      setup(_props: unknown, { emit }: { emit: (event: string, ...args: unknown[]) => void }) {
        onMounted(() => emit('register', {}, 'code-assist-modal'));
      },
      template: '<div data-test="code-assist-modal"><slot /><button data-test="code-assist-ok" @click="$emit(\'ok\')">{{ okText }}</button></div>',
    },
    useModalInner: (init: any) => {
      const instance = getCurrentInstance();
      modalState.init = init;
      return [
        (modal: unknown, uuid: string) => instance?.emit('register', modal, uuid),
        { changeOkLoading: vi.fn(), closeModal: modalState.closeModal },
      ];
    },
  };
});

describe('ELN field code assist modal', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('forwards modal registration to its parent exactly once', () => {
    const onRegister = vi.fn();

    mount(CodeAssistModal, {
      attrs: { onRegister },
      global: { plugins: [Antd] },
      props: { suggestCode: vi.fn() },
    });

    expect(onRegister).toHaveBeenCalledTimes(1);
  });

  it('generates a code from a Chinese name and emits it only after confirmation', async () => {
    const suggestCode = vi.fn(async () => 'fuhe_jieguo');
    const wrapper = mount(CodeAssistModal, {
      global: { plugins: [Antd] },
      props: { suggestCode },
    });
    modalState.init({});

    await wrapper.get('[data-test="code-assist-text"]').setValue('复核结果');
    await wrapper.get('[data-test="code-assist-ok"]').trigger('click');
    await vi.waitFor(() => expect(suggestCode).toHaveBeenCalledWith('复核结果'));

    expect(wrapper.get('[data-test="code-assist-suggestion"]').attributes('value')).toBe('fuhe_jieguo');
    expect(wrapper.emitted('confirm')).toBeUndefined();

    await wrapper.get('[data-test="code-assist-ok"]').trigger('click');

    expect(wrapper.emitted('confirm')).toEqual([['fuhe_jieguo']]);
    expect(modalState.closeModal).toHaveBeenCalled();
  });
});
