import { createHash } from 'node:crypto';
import { readFileSync, statSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');

function sha256(path: string): string {
  return createHash('sha256').update(readFileSync(path)).digest('hex');
}

describe('decoder staging', () => {
  it('copies decoder binaries byte-for-byte without executable permission', () => {
    const threeRoot = resolve(
      dirname(fileURLToPath(import.meta.resolve('three'))),
      '..',
    );
    const ifcRoot = dirname(fileURLToPath(import.meta.resolve('web-ifc')));
    const pairs = [
      [
        resolve(threeRoot, 'examples/jsm/libs/draco/gltf/draco_decoder.wasm'),
        resolve(projectRoot, 'apps/viewer-3d/public/draco/draco_decoder.wasm'),
      ],
      [
        resolve(threeRoot, 'examples/jsm/libs/basis/basis_transcoder.wasm'),
        resolve(projectRoot, 'apps/viewer-3d/public/basis/basis_transcoder.wasm'),
      ],
      [
        resolve(ifcRoot, 'web-ifc.wasm'),
        resolve(projectRoot, 'apps/viewer-3d/public/web-ifc/web-ifc.wasm'),
      ],
    ];

    for (const [source, staged] of pairs) {
      expect(sha256(staged)).toBe(sha256(source));
      expect(statSync(staged).mode & 0o111).toBe(0);
    }
  });
});
