import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

const INSTALLER_PATH = fileURLToPath(new URL('../../../../tools/install.sh', import.meta.url));

async function runInstaller(args: string[]): Promise<{
  status: number | null;
  stderr: string;
  npmCalled: boolean;
}> {
  const home = await mkdtemp(join(tmpdir(), 'mosaic-installer-args-'));
  const bin = join(home, 'bin');
  const npmMarker = join(home, 'npm-called');

  try {
    await mkdir(bin);
    const npmShim = join(bin, 'npm');
    await writeFile(npmShim, `#!/bin/sh\n: > "${npmMarker}"\n`);
    await chmod(npmShim, 0o755);

    const result = spawnSync('bash', [INSTALLER_PATH, ...args], {
      encoding: 'utf8',
      env: {
        ...process.env,
        HOME: home,
        MOSAIC_NO_COLOR: '1',
        PATH: `${bin}:${process.env.PATH ?? ''}`,
      },
    });

    return {
      status: result.status,
      stderr: result.stderr,
      npmCalled: existsSync(npmMarker),
    };
  } finally {
    await rm(home, { recursive: true, force: true });
  }
}

function expectUnknownArgument(result: Awaited<ReturnType<typeof runInstaller>>): void {
  expect(result.status).not.toBe(0);
  expect(result.stderr).toContain('Unknown argument: --bogus');
  expect(result.stderr).toMatch(/Usage: .*install\.sh/);
  expect(result.npmCalled).toBe(false);
}

describe('installer arguments', () => {
  it('rejects an unknown argument before installation starts', async () => {
    expectUnknownArgument(await runInstaller(['--cli', '--bogus']));
  });

  it('does not let --ref consume an unknown option', async () => {
    expectUnknownArgument(await runInstaller(['--cli', '--ref', '--bogus']));
  });
});
