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

import { confirmPublishSubmission } from './approval-application-reason';

const { confirm, prompt } = vi.hoisted(() => ({
  confirm: vi.fn(),
  prompt: vi.fn(),
}));

vi.mock('element-plus', () => ({
  ElMessageBox: {
    confirm,
    prompt,
  },
}));

vi.mock('#/locales', () => ({
  $t: (key: string) => key,
}));

describe('confirmPublishSubmission', () => {
  const api = {
    get: vi.fn(),
  };

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('uses the normal confirmation when no approval flow matches', async () => {
    api.get.mockResolvedValue({ data: false, errorCode: 0 });
    confirm.mockResolvedValue('confirm');

    await expect(
      confirmPublishSubmission({
        api,
        confirmMessage: '确认发布？',
        id: '1',
        resourcePath: '/api/v1/workflow',
        title: '提示',
      }),
    ).resolves.toEqual({});

    expect(confirm).toHaveBeenCalled();
    expect(prompt).not.toHaveBeenCalled();
  });

  it('requires and trims a reason when an approval flow matches', async () => {
    api.get.mockResolvedValue({ data: true, errorCode: 0 });
    prompt.mockResolvedValue({ value: '  本次修复复制兼容问题  ' });

    await expect(
      confirmPublishSubmission({
        api,
        confirmMessage: '确认提交发布审批？',
        id: '1',
        resourcePath: '/api/v1/workflow',
        title: '提示',
      }),
    ).resolves.toEqual({
      applicationReason: '本次修复复制兼容问题',
    });

    const promptOptions = prompt.mock.calls[0]?.[2];
    expect(promptOptions.inputValidator('   ')).toBe(
      'approval.message.applicationReasonRequired',
    );
    expect(promptOptions.inputValidator('a'.repeat(501))).toBe(
      'approval.message.applicationReasonTooLong',
    );
    expect(promptOptions.inputValidator('有效说明')).toBe(true);
  });

  it('returns null when the user cancels', async () => {
    api.get.mockResolvedValue({ data: true, errorCode: 0 });
    prompt.mockRejectedValue(new Error('cancel'));

    await expect(
      confirmPublishSubmission({
        api,
        confirmMessage: '确认提交发布审批？',
        id: '1',
        resourcePath: '/api/v1/workflow',
        title: '提示',
      }),
    ).resolves.toBeNull();
  });
});
