import { afterEach, describe, it } from 'node:test';
import { strict as assert } from 'node:assert';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { runMxCli, parseLastJson, assertExitCode } from '../helpers/cli-harness.js';
import { createMatrixPackage } from '../helpers/package-fixtures.js';

describe('FP-30 mx pack command', () => {
  const tempDirs: string[] = [];

  afterEach(() => {
    while (tempDirs.length > 0) {
      const dir = tempDirs.pop();
      if (dir) {
        fs.rmSync(dir, { recursive: true, force: true });
      }
    }
  });

  it('creates distributable tarball with package identity metadata', async () => {
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mx-fp30-pack-'));
    tempDirs.push(root);

    const fixture = createMatrixPackage(root, {
      packageName: '@acme/fp30-pack',
      version: '2.3.4',
      componentType: 'PackActor',
      mount: 'fp30.pack',
    });
    const outDir = path.join(root, 'dist-pack');

    const result = await runMxCli([
      'node',
      'mx',
      'pack',
      '--out-dir',
      outDir,
      '--json',
    ], { cwd: fixture.packageDir });

    assertExitCode(result, 0);
    const payload = parseLastJson(result.logs) as {
      packageName: string;
      version: string;
      tarballPath: string;
    };
    assert.equal(payload.packageName, fixture.packageName);
    assert.equal(payload.version, fixture.version);
    assert.equal(fs.existsSync(payload.tarballPath), true);
    assert.equal(payload.tarballPath.endsWith('.tar.gz'), true);
  });
});
