import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
  ALLOWED_BLOB_MIME_TYPES,
  FALLBACK_MIMETYPE,
  getBlobSafeMimeType,
  safeFile,
  mimeTypeToExt,
  getFileNameExt,
  getFileNameWithoutExt,
} from './mimeTypes';

test('getBlobSafeMimeType falls back for disallowed types', () => {
  assert.equal(getBlobSafeMimeType('application/x-totally-not-allowed'), FALLBACK_MIMETYPE);
  // non-string input is coerced to the fallback
  assert.equal(getBlobSafeMimeType(undefined as unknown as string), FALLBACK_MIMETYPE);
});

test('getBlobSafeMimeType passes allowed types and strips codec params', () => {
  const allowed = ALLOWED_BLOB_MIME_TYPES[0];
  assert.equal(getBlobSafeMimeType(allowed), allowed);
  // everything after the first ';' is dropped
  assert.equal(getBlobSafeMimeType(`${allowed}; charset=utf-8`), allowed);
});

test('getBlobSafeMimeType remaps quicktime/ogg (when allowlisted)', () => {
  if (ALLOWED_BLOB_MIME_TYPES.includes('video/quicktime')) {
    assert.equal(getBlobSafeMimeType('video/quicktime'), 'video/mp4');
  }
  if (ALLOWED_BLOB_MIME_TYPES.includes('application/ogg')) {
    assert.equal(getBlobSafeMimeType('application/ogg'), 'audio/ogg');
  }
});

test('safeFile rewraps a file whose type is not blob-safe', () => {
  const f = new File(['x'], 'note.txt', { type: 'application/x-bad' });
  const safe = safeFile(f);
  assert.equal(safe.type, FALLBACK_MIMETYPE);
  assert.equal(safe.name, 'note.txt');
});

test('mimeTypeToExt returns the subtype', () => {
  assert.equal(mimeTypeToExt('image/png'), 'png');
  assert.equal(mimeTypeToExt('application/vnd.ms-excel'), 'vnd.ms-excel');
});

test('getFileNameExt', () => {
  assert.equal(getFileNameExt('photo.PNG'), 'PNG');
  assert.equal(getFileNameExt('archive.tar.gz'), 'gz');
  // no dot → returns the whole name (lastIndexOf('.') === -1 → slice(0))
  assert.equal(getFileNameExt('noext'), 'noext');
});

test('getFileNameWithoutExt', () => {
  assert.equal(getFileNameWithoutExt('photo.png'), 'photo');
  assert.equal(getFileNameWithoutExt('a.b.c'), 'a.b');
  assert.equal(getFileNameWithoutExt('noext'), 'noext');
  // a leading-dot dotfile keeps its name (extStart === 0)
  assert.equal(getFileNameWithoutExt('.hidden'), '.hidden');
});
