import { describe, it, expect, beforeAll } from 'vitest';
import type { MediaItem } from '@features/media/types';
import { createImageBlockAttrs, createFileBlockAttrs, buildMediaBlockContent } from './mediaBlockContent';

const createMediaItem = (overrides: Partial<MediaItem> = {}): MediaItem =>
  ({
    media_id: 1,
    media_type: 'image',
    media_thumbnail: 'thumb.jpg',
    media_root_path: 'media/1.jpg',
    media_size: '800x600',
    media_permalink: 'media/1.jpg',
    media_icon: 'icon.png',
    ...overrides,
  }) as MediaItem;

beforeAll(() => {
  const target = window as unknown as { ACMS?: Record<string, unknown> };
  target.ACMS = { ...target.ACMS, Config: { eid: '42' } };
});

describe('createImageBlockAttrs', () => {
  it('media_size から width/height を数値で取り出す', () => {
    const attrs = createImageBlockAttrs(createMediaItem({ media_size: '800x600' }), 'cls');
    expect(attrs.width).toBe(800);
    expect(attrs.height).toBe(600);
    expect(attrs.src).toBe('media/1.jpg');
    expect(attrs.class).toBe('cls');
    expect(attrs.mediaId).toBe(1);
  });

  it('media_size に x が無ければ width/height は null、className 未指定で class は null', () => {
    const attrs = createImageBlockAttrs(createMediaItem({ media_size: '' }));
    expect(attrs.width).toBeNull();
    expect(attrs.height).toBeNull();
    expect(attrs.class).toBeNull();
  });
});

describe('createFileBlockAttrs', () => {
  it('ファイル属性を組み立て、アイコンサイズ未指定時は 100 を既定にする', () => {
    const attrs = createFileBlockAttrs(
      createMediaItem({ media_type: 'file', media_permalink: 'media/a.pdf', media_icon: 'pdf.png', media_ext: 'pdf' }),
      'cls'
    );
    expect(attrs.href).toBe('media/a.pdf');
    expect(attrs.icon).toBe('pdf.png');
    expect(attrs.iconWidth).toBe('100');
    expect(attrs.iconHeight).toBe('100');
    expect(attrs.extension).toBe('pdf');
    expect(attrs.class).toBe('cls');
  });
});

describe('buildMediaBlockContent', () => {
  it('media_type=image は imageBlock を返し noLightbox を付与する', () => {
    const content = buildMediaBlockContent(createMediaItem({ media_type: 'image' }), '', 'true');
    expect(content.type).toBe('imageBlock');
    expect(content.attrs.noLightbox).toBe('true');
  });

  it('media_type=svg も imageBlock として扱う', () => {
    const content = buildMediaBlockContent(createMediaItem({ media_type: 'svg' }), '', 'false');
    expect(content.type).toBe('imageBlock');
  });

  it('media_type=file は fileBlock を返し noLightbox を持たない', () => {
    const content = buildMediaBlockContent(createMediaItem({ media_type: 'file' }), '', 'true');
    expect(content.type).toBe('fileBlock');
    expect(content.attrs.noLightbox).toBeUndefined();
  });
});
