import type { ChatTimelineArtifactItem } from '../types';

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

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

import ChatArtifactAttachment from '../ChatArtifactAttachment.vue';

function artifact(
  status: ChatTimelineArtifactItem['status'] = 'available',
): ChatTimelineArtifactItem {
  return {
    artifactId: '01JTESTARTIFACT',
    downloadUrl:
      status === 'available'
        ? '/api/v1/agent/artifacts/01JTESTARTIFACT/content'
        : undefined,
    fileName: '项目报告.pdf',
    id: 'artifact:01JTESTARTIFACT',
    mimeType: 'application/pdf',
    sha256: 'a'.repeat(64),
    size: 2048,
    status,
    type: 'artifact',
  };
}

describe('chat Artifact attachment', () => {
  it('支持鉴权下载、失败提示和原位重试', async () => {
    const loader = vi
      .fn()
      .mockRejectedValueOnce(new Error('网络中断'))
      .mockResolvedValueOnce(undefined);
    const wrapper = mount(ChatArtifactAttachment, {
      props: { artifactLoader: loader, item: artifact() },
    });

    await wrapper.get('button').trigger('click');
    await flushPromises();
    expect(wrapper.text()).toContain('网络中断，点击重试');
    expect(wrapper.get('button').attributes('aria-label')).toContain(
      '重试下载',
    );

    await wrapper.get('button').trigger('click');
    await flushPromises();
    expect(loader).toHaveBeenCalledTimes(2);
    expect(wrapper.text()).toContain('PDF · 2 KB');
  });

  it.each([
    ['expired', '已过期'],
    ['delete_failed', '删除失败'],
    ['unavailable', '不可用'],
  ] as const)('展示 %s 状态并禁用下载', (status, label) => {
    const loader = vi.fn();
    const wrapper = mount(ChatArtifactAttachment, {
      props: { artifactLoader: loader, item: artifact(status) },
    });

    expect(wrapper.text()).toContain(label);
    expect(wrapper.get('button').attributes('disabled')).toBeDefined();
    expect(wrapper.html()).not.toMatch(/MinIO|bucket|objectKey|workspace/i);
  });
});
