import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';

import {
  assertClassicLevelPrebuild,
  CLASSIC_LEVEL_PREBUILD_KEYS,
  ensureReleaseNativeDeps,
  sharpImgPackagesToInstall,
  WIN_SHARP_IMG_PACKAGES,
} from './release-native-prep.mjs';

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

void test('CLASSIC_LEVEL_PREBUILD_KEYS covers win/mac/linux', () => {
  assert.deepEqual(CLASSIC_LEVEL_PREBUILD_KEYS.win, ['win32-x64']);
  assert.ok(CLASSIC_LEVEL_PREBUILD_KEYS.mac.includes('darwin-x64+arm64'));
  assert.ok(CLASSIC_LEVEL_PREBUILD_KEYS.linux.includes('linux-x64'));
  assert.ok(CLASSIC_LEVEL_PREBUILD_KEYS.linux.includes('linux-arm64'));
});

void test('assertClassicLevelPrebuild: win32-x64 present after npm ci', () => {
  assertClassicLevelPrebuild(root, 'win32-x64');
});

void test('ensureReleaseNativeDeps(win): does not throw when prebuilds present', () => {
  ensureReleaseNativeDeps(root, 'win', { runInstall: false });
});

void test('sharpImgPackagesToInstall: lists missing win32-x64 when absent', () => {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'native-prep-'));
  try {
    const sharpOpt = {
      '@img/sharp-win32-x64': '0.34.5',
    };
    fs.mkdirSync(path.join(tmp, 'node_modules', 'sharp'), { recursive: true });
    fs.writeFileSync(
      path.join(tmp, 'node_modules', 'sharp', 'package.json'),
      JSON.stringify({ optionalDependencies: sharpOpt }),
    );
    const missing = sharpImgPackagesToInstall(tmp, WIN_SHARP_IMG_PACKAGES);
    assert.deepEqual(missing, ['@img/sharp-win32-x64@0.34.5']);
  } finally {
    fs.rmSync(tmp, { recursive: true, force: true });
  }
});
