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');
const legacyPublicResourceRoot = path.resolve(process.cwd(), '../../../public/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();
  }
});

test('resource manager preview falls back to public/resource legacy artifacts', async () => {
  const app = Fastify();
  await registerResourceManagerRoutes(app);

  const relativePath = path.join('legacy-preview-test', `sample-${Date.now()}.html`);
  const absolutePath = path.join(legacyPublicResourceRoot, relativePath);
  await fs.mkdir(path.dirname(absolutePath), { recursive: true });
  await fs.writeFile(absolutePath, '<!doctype html><html><body>legacy preview</body></html>', 'utf8');

  try {
    const response = await app.inject({
      method: 'GET',
      url: `/api/resource-manager/preview/${relativePath.split(path.sep).map((segment) => encodeURIComponent(segment)).join('/')}?token=${encodeURIComponent(env.SERVER_COMMAND_ACCESS_TOKEN)}`,
    });

    assert.equal(response.statusCode, 200);
    assert.match(String(response.headers['content-type'] ?? ''), /text\/html/i);
    assert.match(response.body, /legacy preview/);
  } finally {
    await fs.rm(path.join(legacyPublicResourceRoot, 'legacy-preview-test'), { recursive: true, force: true });
    await app.close();
  }
});

test('resource manager preview restores encoded hash fragments in the file name', async () => {
  const app = Fastify();
  await registerResourceManagerRoutes(app);

  const relativePath = path.join('encoded-preview-test', `sample-${Date.now()}.html`);
  const absolutePath = path.join(legacyPublicResourceRoot, relativePath);
  await fs.mkdir(path.dirname(absolutePath), { recursive: true });
  await fs.writeFile(absolutePath, '<!doctype html><html><body>encoded hash preview</body></html>', 'utf8');

  try {
    for (const encodedSuffix of ['%23option-a', '%2523option-a']) {
      const encodedPath = relativePath
        .split(path.sep)
        .map((segment, index, list) =>
          index === list.length - 1
            ? `${encodeURIComponent(segment)}${encodedSuffix}`
            : encodeURIComponent(segment),
        )
        .join('/');
      const response = await app.inject({
        method: 'GET',
        url: `/api/resource-manager/preview/${encodedPath}?token=${encodeURIComponent(env.SERVER_COMMAND_ACCESS_TOKEN)}`,
      });

      assert.equal(response.statusCode, 200);
      assert.match(String(response.headers['content-type'] ?? ''), /text\/html/i);
      assert.match(response.body, /encoded hash preview/);
    }
  } finally {
    await fs.rm(path.join(legacyPublicResourceRoot, 'encoded-preview-test'), { recursive: true, force: true });
    await app.close();
  }
});
