import assert from "node:assert/strict";
import test from "node:test";
import { createAudioApi } from "../../lib/server/audio-api.ts";

function setup() {
  const bytes = new Uint8Array([0x49, 0x44, 0x33, 1, 2, 3, 4, 5, 6, 7]);
  const ranges = [];
  const api = createAudioApi({
    repository: {
      objectForAudio: async () => ({ objectKey: "audio/current.mp3", audio: { bytes: bytes.length } }),
    },
    bucket: {
      get: async (_key, options) => {
        ranges.push(options?.range ?? null);
        const range = options?.range;
        if (!range) return { body: bytes, size: bytes.length, httpEtag: '"etag"' };
        const length = range.length ?? bytes.length - range.offset;
        const body = bytes.slice(range.offset, range.offset + length);
        return { body, size: bytes.length, range: { ...range, length }, httpEtag: '"etag"' };
      },
    },
  });
  return { api, ranges };
}

test("serves one bounded byte range so mobile audio can seek", async () => {
  const { api, ranges } = setup();
  const response = await api.stream(
    new Request("https://example.test/audio", { headers: { range: "bytes=3-6" } }),
    "segment-1",
    "voice",
  );
  assert.equal(response.status, 206);
  assert.deepEqual(ranges, [{ offset: 3, length: 4 }]);
  assert.equal(response.headers.get("accept-ranges"), "bytes");
  assert.equal(response.headers.get("content-range"), "bytes 3-6/10");
  assert.equal(response.headers.get("content-length"), "4");
  assert.deepEqual([...new Uint8Array(await response.arrayBuffer())], [1, 2, 3, 4]);
});

test("rejects malformed or multiple ranges", async () => {
  const { api } = setup();
  assert.equal((await api.stream(new Request("https://example.test", { headers: { range: "bytes=5-2" } }), "s", "voice")).status, 416);
  assert.equal((await api.stream(new Request("https://example.test", { headers: { range: "bytes=1-2,4-5" } }), "s", "voice")).status, 416);
});

test("accepts the open-ended range used by Edge audio elements", async () => {
  const { api, ranges } = setup();
  const response = await api.stream(
    new Request("https://example.test/audio", { headers: { range: "bytes=3-" } }),
    "segment-1",
    "voice",
  );
  assert.equal(response.status, 206);
  assert.deepEqual(ranges, [{ offset: 3 }]);
  assert.equal(response.headers.get("content-range"), "bytes 3-9/10");
  assert.equal(response.headers.get("content-length"), "7");
});
