import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';

import sharp from 'sharp';

import { generateScenePreviewThumbnailBytes, SCENE_PREVIEW_THUMB_MAX_PX } from './scenePreviewThumbnail';

void test('generateScenePreviewThumbnailBytes: image scales to max edge', async () => {
  const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-thumb-test-'));
  const src = path.join(tmp, 'wide.png');
  await sharp({
    create: {
      width: 800,
      height: 400,
      channels: 3,
      background: { r: 200, g: 40, b: 40 },
    },
  })
    .png()
    .toFile(src);

  const buf = await generateScenePreviewThumbnailBytes(src, 'image');
  assert.ok(buf !== null);
  assert.ok(buf.length > 0);
  const meta = await sharp(buf).metadata();
  assert.equal(typeof meta.width, 'number');
  assert.equal(typeof meta.height, 'number');
  assert.ok(meta.width > 0 && meta.height > 0);
  assert.ok(Math.max(meta.width, meta.height) <= SCENE_PREVIEW_THUMB_MAX_PX);

  await fs.rm(tmp, { recursive: true, force: true });
});

void test('generateScenePreviewThumbnailBytes: accepts image Buffer', async () => {
  const png = await sharp({
    create: {
      width: 120,
      height: 80,
      channels: 3,
      background: { r: 10, g: 20, b: 30 },
    },
  })
    .png()
    .toBuffer();
  const buf = await generateScenePreviewThumbnailBytes(png, 'image');
  assert.ok(buf !== null);
  assert.ok(buf.length > 0);
});
