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

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

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

vi.mock('../auth/index.js', () => ({
  loadStoredOpenAIAuth: mockLoadStoredOpenAIAuth,
  loginOpenAI: mockLoginOpenAI,
}));

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('openai-auth command', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockLoadStoredOpenAIAuth.mockReset();
    mockLoginOpenAI.mockReset();
    mockCreateInterface.mockReset();
  });

  it('cancels when OAuth token exists and user answers no', async () => {
    mockLoadStoredOpenAIAuth.mockReturnValue({ access_token: 'at', refresh_token: 'rt', expires_at: Date.now() + 1000, created_at: new Date().toISOString() });
    mockReadlineAnswers(['n']);

    const program = new Command();
    const { registerOpenaiAuthCommand } = await import('./openai-auth.js');
    registerOpenaiAuthCommand(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', 'openai-auth'])).rejects.toThrow('EXIT:0');
    expect(mockLoginOpenAI).not.toHaveBeenCalled();
    expect(consoleLog).toHaveBeenCalledWith('Cancelled.');

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

  it('starts login flow when user confirms re-authentication', async () => {
    mockLoadStoredOpenAIAuth.mockReturnValue({ access_token: 'at', refresh_token: 'rt', expires_at: Date.now() + 1000, created_at: new Date().toISOString() });
    mockReadlineAnswers(['y']);
    mockLoginOpenAI.mockResolvedValue(undefined);

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

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

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

    expect(mockLoginOpenAI).toHaveBeenCalledOnce();
    expect(consoleError).not.toHaveBeenCalled();

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