import { Command } from 'commander';
import { beforeEach, describe, expect, it, vi } from 'vitest';

const { mockExistsSync } = vi.hoisted(() => ({
  mockExistsSync: vi.fn(() => false),
}));

const { mockCreateInterface } = vi.hoisted(() => ({
  mockCreateInterface: vi.fn(),
}));

const { mockCreatePrompter, mockConfirm } = vi.hoisted(() => ({
  mockCreatePrompter: vi.fn(),
  mockConfirm: vi.fn(async () => false),
}));

vi.mock('fs', () => ({
  existsSync: mockExistsSync,
}));

vi.mock('readline/promises', () => ({
  createInterface: mockCreateInterface,
}));

vi.mock('./setup/prompts.js', () => ({
  createPrompter: mockCreatePrompter,
}));

describe('start command', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockExistsSync.mockReset();
    mockExistsSync.mockReturnValue(false);
    mockConfirm.mockReset();
    mockConfirm.mockResolvedValue(false);
    mockCreateInterface.mockReset();
    mockCreateInterface.mockReturnValue({ close: vi.fn() });
    mockCreatePrompter.mockReset();
    mockCreatePrompter.mockReturnValue({
      confirm: mockConfirm,
    });
  });

  it('suggests onboard/setup guidance when config is missing and wizard is declined', async () => {
    const program = new Command();
    const { registerStartCommand } = await import('./start.js');
    registerStartCommand(program);

    const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
    const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
      throw new Error(`EXIT:${code ?? 0}`);
    }) as never);

    await expect(
      program.parseAsync(['node', 'test', 'start', '--config', '/tmp/missing.yaml']),
    ).rejects.toThrow('EXIT:1');

    expect(consoleError).toHaveBeenCalledWith(
      'Run "flynn onboard" (or "flynn setup") to create one, or "flynn doctor" to diagnose.',
    );

    exitSpy.mockRestore();
    consoleError.mockRestore();
  });
});
