import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import Fastify from 'fastify';
import { env } from '../config/env.js';
import { registerResourceManagerRoutes, resolveSingleRange } from './resource-manager.js';

const fallbackResourceRoot = path.resolve(process.cwd(), '../../../resource');

test('resolveSingleRange parses open-ended and suffix byte ranges', () => {
  assert.deepEqual(resolveSingleRange('bytes=5-', 20), {
    isValid: true,
    start: 5,
    end: 19,
  });
  assert.deepEqual(resolveSingleRange('bytes=-4', 20), {
    isValid: true,
    start: 16,
    end: 19,
  });
});

test('resolveSingleRange rejects malformed or out-of-bounds values', () => {
  assert.deepEqual(resolveSingleRange('bytes=', 20), { isValid: false });
  assert.deepEqual(resolveSingleRange('bytes=25-30', 20), { isValid: false });
  assert.deepEqual(resolveSingleRange('bytes=4-3', 20), { isValid: false });
});

test('resource manager preview serves 206 partial content for byte ranges', async () => {
  const app = Fastify();
  await registerResourceManagerRoutes(app);

  const relativePath = `range-test-${Date.now()}.wav`;
  const absolutePath = path.join(fallbackResourceRoot, relativePath);
  await fs.mkdir(path.dirname(absolutePath), { recursive: true });
  await fs.writeFile(absolutePath, Buffer.from('0123456789', 'utf8'));

  try {
    const response = await app.inject({
      method: 'GET',
      url: `/api/resource-manager/preview/${encodeURIComponent(relativePath)}?token=${encodeURIComponent(env.SERVER_COMMAND_ACCESS_TOKEN)}`,
      headers: {
        range: 'bytes=2-5',
      },
    });

    assert.equal(response.statusCode, 206);
    assert.equal(response.headers['accept-ranges'], 'bytes');
    assert.equal(response.headers['content-range'], 'bytes 2-5/10');
    assert.equal(response.headers['content-length'], '4');
    assert.equal(response.body, '2345');
  } finally {
    await fs.rm(absolutePath, { force: true });
    await app.close();
  }
});
