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

import {
  buildWorkflowImageValueFromResource,
  buildWorkflowImageValueFromUpload,
  buildWorkflowImageValueFromUrl,
  hasWorkflowImageValue,
  normalizeWorkflowImageValue,
  validateWorkflowImageFile,
} from '../workflowImageValue';

describe('workflowImageValue', () => {
  it('构建并归一化 URL 图片值', () => {
    expect(buildWorkflowImageValueFromUrl('https://example.com/a.png')).toEqual({
      sourceType: 'url',
      url: 'https://example.com/a.png',
    });
    expect(normalizeWorkflowImageValue('https://example.com/a.png')).toEqual({
      sourceType: 'url',
      url: 'https://example.com/a.png',
    });
  });

  it('构建上传和素材图片值', () => {
    const file = new File(['image'], 'a.png', { type: 'image/png' });
    expect(buildWorkflowImageValueFromUpload(file, '/files/a.png')).toMatchObject({
      sourceType: 'upload',
      fileName: 'a.png',
      filePath: '/files/a.png',
    });
    expect(
      buildWorkflowImageValueFromResource({
        fileSize: '128',
        resourceName: 'asset',
        resourceType: 0,
        resourceUrl: '/files/asset.webp',
        suffix: 'webp',
      }),
    ).toMatchObject({
      sourceType: 'resource',
      fileName: 'asset.webp',
      filePath: '/files/asset.webp',
      size: 128,
    });
  });

  it('兼容旧文件对象并执行内容感知必填判断', () => {
    const legacy = {
      fileName: 'legacy.jpg',
      filePath: '/files/legacy.jpg',
      contentType: 'image/jpeg',
    };
    expect(normalizeWorkflowImageValue(legacy)).toMatchObject({
      sourceType: 'upload',
      fileName: 'legacy.jpg',
    });
    expect(hasWorkflowImageValue(legacy)).toBe(true);
    expect(hasWorkflowImageValue({})).toBe(false);
  });

  it('校验图片格式与 10 MiB 边界', () => {
    const accepted = new File(
      [new Uint8Array(10 * 1024 * 1024)],
      'accepted.png',
      { type: 'image/png' },
    );
    const oversized = new File(
      [new Uint8Array(10 * 1024 * 1024 + 1)],
      'oversized.png',
      { type: 'image/png' },
    );
    expect(() => validateWorkflowImageFile(accepted)).not.toThrow();
    expect(() => validateWorkflowImageFile(oversized)).toThrow(
      '单张图片不能超过 10 MiB',
    );
    expect(() =>
      validateWorkflowImageFile(
        new File(['text'], 'note.txt', { type: 'text/plain' }),
      ),
    ).toThrow('仅支持 PNG、JPEG、WebP、GIF、BMP 图片');
  });
});
