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 { macSharpImgPackagesToInstall } from './release-mac-prep.mjs';

void test('macSharpImgPackagesToInstall: empty when all four @img darwin packages exist', () => {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-sharp-all-'));
  try {
    const sharpOpt = {
      '@img/sharp-darwin-arm64': '0.34.5',
      '@img/sharp-libvips-darwin-arm64': '1.2.4',
      '@img/sharp-darwin-x64': '0.34.5',
      '@img/sharp-libvips-darwin-x64': '1.2.4',
    };
    fs.mkdirSync(path.join(tmp, 'node_modules', 'sharp'), { recursive: true });
    fs.writeFileSync(
      path.join(tmp, 'node_modules', 'sharp', 'package.json'),
      JSON.stringify({ optionalDependencies: sharpOpt }),
    );
    for (const name of Object.keys(sharpOpt)) {
      const dir = path.join(tmp, 'node_modules', name);
      fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(path.join(dir, 'package.json'), '{}');
    }
    const missing = macSharpImgPackagesToInstall(tmp);
    assert.deepEqual(missing, []);
  } finally {
    fs.rmSync(tmp, { recursive: true, force: true });
  }
});

void test('macSharpImgPackagesToInstall: lists missing darwin-x64 on arm64-only tree', () => {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-sharp-prep-'));
  try {
    const sharpOpt = {
      '@img/sharp-darwin-arm64': '0.34.5',
      '@img/sharp-libvips-darwin-arm64': '1.2.4',
      '@img/sharp-darwin-x64': '0.34.5',
      '@img/sharp-libvips-darwin-x64': '1.2.4',
    };
    fs.mkdirSync(path.join(tmp, 'node_modules', 'sharp'), { recursive: true });
    fs.writeFileSync(
      path.join(tmp, 'node_modules', 'sharp', 'package.json'),
      JSON.stringify({ optionalDependencies: sharpOpt }),
    );
    for (const name of ['@img/sharp-darwin-arm64', '@img/sharp-libvips-darwin-arm64']) {
      const dir = path.join(tmp, 'node_modules', name);
      fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(path.join(dir, 'package.json'), '{}');
    }

    const missing = macSharpImgPackagesToInstall(tmp);
    assert.deepEqual(missing, ['@img/sharp-darwin-x64@0.34.5', '@img/sharp-libvips-darwin-x64@1.2.4']);
  } finally {
    fs.rmSync(tmp, { recursive: true, force: true });
  }
});
