import assert from 'node:assert/strict';
import test from 'node:test';

import sharp from 'sharp';

import { optimizeImageBufferVisuallyLossless } from './optimizeImageImport.lib.mjs';

void test('optimizeImageBufferVisuallyLossless: preserves dimensions for opaque RGB', async () => {
  const input = await sharp({
    create: {
      width: 400,
      height: 300,
      channels: 3,
      background: { r: 10, g: 100, b: 200 },
    },
  })
    .png({ compressionLevel: 0 })
    .toBuffer();

  const out = await optimizeImageBufferVisuallyLossless(input);
  assert.equal(out.passthrough, false);
  assert.ok(out.buffer.length > 0);
  assert.ok(out.buffer.length < input.length);
  const meta = await sharp(out.buffer).metadata();
  assert.equal(meta.width, 400);
  assert.equal(meta.height, 300);
});

void test('optimizeImageBufferVisuallyLossless: preserves dimensions for alpha', async () => {
  const input = await sharp({
    create: {
      width: 200,
      height: 200,
      channels: 4,
      background: { r: 255, g: 0, b: 0, alpha: 0.5 },
    },
  })
    .png({ compressionLevel: 0 })
    .toBuffer();

  const out = await optimizeImageBufferVisuallyLossless(input);
  assert.equal(out.passthrough, false);
  assert.ok(out.mime === 'image/webp' || out.mime === 'image/png');
  assert.ok(out.buffer.length < input.length);
  const meta = await sharp(out.buffer).metadata();
  assert.equal(meta.width, 200);
  assert.equal(meta.height, 200);
  assert.equal(meta.hasAlpha, true);
});

void test('optimizeImageBufferVisuallyLossless: non-image buffer is passthrough', async () => {
  const out = await optimizeImageBufferVisuallyLossless(Buffer.from('not an image'));
  assert.equal(out.passthrough, true);
});
