import { 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 { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { cqrsCommand } from '../../src/commands/cqrs.js';
import { installOpenMatrixCoreStub } from '../support/installCoreStub.ts';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '../../../../');

describe('FP-30 mx cqrs scaffold', () => {
  it('creates command/query archetype package', async () => {
    const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mx-cqrs-'));
    const outputDir = path.join(tmpRoot, 'orders-cqrs');

    try {
      const result = await cqrsCommand('orders-cqrs', {
        cwd: repoRoot,
        outputDir,
      });

      assert.equal(fs.existsSync(path.join(outputDir, 'matrix.json')), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'src', `${result.commandClassName}.ts`)), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'src', `${result.queryClassName}.ts`)), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'examples', 'execute.mxq')), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'examples', 'query.mxq')), true);

      const manifest = JSON.parse(fs.readFileSync(path.join(outputDir, 'matrix.json'), 'utf8')) as {
        components: Array<{ mount?: string; type?: string }>;
      };
      assert.equal(manifest.components.length, 2);
      assert.equal(manifest.components.some((entry) => entry.mount === 'orders-cqrs.command'), true);
      assert.equal(manifest.components.some((entry) => entry.mount === 'orders-cqrs.query'), true);

      installOpenMatrixCoreStub(outputDir);

      const compile = spawnSync(
        process.execPath,
        [
          path.resolve(repoRoot, 'node_modules/tsx/dist/cli.mjs'),
          path.join(outputDir, 'src', 'index.ts'),
        ],
        { cwd: outputDir, encoding: 'utf8' }
      );
      assert.equal(compile.status, 0, compile.stderr || '(no stderr)');
    } finally {
      fs.rmSync(tmpRoot, { recursive: true, force: true });
    }
  });
});
