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

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

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

vi.mock('../auth/index.js', () => ({
  loadStoredZaiAuth: mockLoadStoredZaiAuth,
  storeZaiAuth: mockStoreZaiAuth,
}));

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

function mockReadlineAnswers(answers: string[]): void {
  const queue = [...answers];
  mockCreateInterface.mockImplementation(() => ({
    question: (_prompt: string, cb: (answer: string) => void) => cb(queue.shift() ?? ''),
    close: () => undefined,
  }));
}

describe('zai-auth command', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockLoadStoredZaiAuth.mockReset();
    mockStoreZaiAuth.mockReset();
    mockCreateInterface.mockReset();
  });

  it('cancels when credential exists and user answers no', async () => {
    mockLoadStoredZaiAuth.mockReturnValue({ api_key: 'existing-key', created_at: '2026-02-16T00:00:00.000Z' });
    mockReadlineAnswers(['n']);

    const program = new Command();
    const { registerZaiAuthCommand } = await import('./zai-auth.js');
    registerZaiAuthCommand(program);

    const consoleLog = vi.spyOn(console, 'log').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', 'zai-auth'])).rejects.toThrow('EXIT:0');
    expect(mockStoreZaiAuth).not.toHaveBeenCalled();
    expect(consoleLog).toHaveBeenCalledWith('Cancelled.');

    exitSpy.mockRestore();
    consoleLog.mockRestore();
  });

  it('re-prompts and stores new key when credential exists and user answers yes', async () => {
    mockLoadStoredZaiAuth.mockReturnValue({ api_key: 'existing-key', created_at: '2026-02-16T00:00:00.000Z' });
    mockReadlineAnswers(['y', '1', 'new-zai-key']);

    const program = new Command();
    const { registerZaiAuthCommand } = await import('./zai-auth.js');
    registerZaiAuthCommand(program);

    const consoleLog = vi.spyOn(console, 'log').mockImplementation(() => undefined);
    const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);

    await program.parseAsync(['node', 'test', 'zai-auth']);

    expect(mockStoreZaiAuth).toHaveBeenCalledWith('new-zai-key');
    expect(consoleError).not.toHaveBeenCalled();

    consoleLog.mockRestore();
    consoleError.mockRestore();
  });

  it('supports --mode plan without interactive mode selection', async () => {
    mockLoadStoredZaiAuth.mockReturnValue(null);
    mockReadlineAnswers(['new-zai-plan-key']);

    const program = new Command();
    const { registerZaiAuthCommand } = await import('./zai-auth.js');
    registerZaiAuthCommand(program);

    const consoleLog = vi.spyOn(console, 'log').mockImplementation(() => undefined);
    const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);

    await program.parseAsync(['node', 'test', 'zai-auth', '--mode', 'plan']);

    expect(mockStoreZaiAuth).toHaveBeenCalledWith('new-zai-plan-key');
    expect(consoleError).not.toHaveBeenCalled();

    consoleLog.mockRestore();
    consoleError.mockRestore();
  });
});
