const test = require("node:test");
const assert = require("node:assert/strict");
const { directAudioUploadLimitBytes, validateAudioUpload, validateAudioContent } = require("../src/security/audioUpload");

test("audio metadata accepts supported files", () => {
  assert.doesNotThrow(() => validateAudioUpload({ originalFilename: "session.webm", mimetype: "audio/webm", size: 1024 }));
});

test("audio metadata rejects unsupported MIME and extension", () => {
  assert.throws(() => validateAudioUpload({ originalFilename: "payload.exe", mimetype: "application/octet-stream", size: 1024 }), { code: 415 });
  assert.throws(() => validateAudioUpload({ originalFilename: "payload.mp3.exe", mimetype: "audio/mpeg", size: 1024 }), { code: 415 });
});

test("audio metadata rejects empty and oversized uploads", () => {
  assert.throws(() => validateAudioUpload({ originalFilename: "empty.mp3", mimetype: "audio/mpeg", size: 0 }), { code: 413 });
  assert.throws(() => validateAudioUpload({ originalFilename: "large.mp3", mimetype: "audio/mpeg", size: directAudioUploadLimitBytes + 1 }), { code: 413 });
});

test("audio content accepts a decoded audio stream", async () => {
  const probe = async (command, argumentsList) => {
    assert.equal(command, "ffprobe");
    assert.equal(argumentsList.at(-1), "/tmp/session.mp3");
    return { stdout: "audio\n" };
  };
  await assert.doesNotReject(validateAudioContent("/tmp/session.mp3", probe));
});

test("audio content rejects files without an audio stream", async () => {
  const noAudioProbe = async () => ({ stdout: "video\n" });
  await assert.rejects(validateAudioContent("/tmp/payload.mp3", noAudioProbe), { code: 415 });
});

test("audio content rejects files ffprobe cannot decode", async () => {
  const failedProbe = async () => {
    throw new Error("Invalid data found when processing input");
  };
  await assert.rejects(validateAudioContent("/tmp/payload.mp3", failedProbe), { code: 415 });
});
