import { password } from '@inquirer/prompts';
import { ENTER_PASS } from '../constants/message-constants.js';
import { passwordPrompt } from './input-prompt.js';

jest.mock('@inquirer/prompts', () => ({
    password: jest.fn(),
}));

describe('input-prompt test suite', () => {
    afterEach(() => {
        jest.clearAllMocks();
    });

    it('should return the provided password if inputPassword is given', async () => {
        const providedPassword = 'xyz';
        const result = await passwordPrompt(providedPassword);
        expect(result).toBe(providedPassword);
        expect(password).not.toHaveBeenCalled();
    });

    it('should prompt for a password and return it if inputPassword is not provided', async () => {
        const userInput = 'xyz';
        (password as jest.Mock).mockResolvedValue(userInput);

        const result = await passwordPrompt(undefined);
        expect(result).toBe(userInput);
        expect(password).toHaveBeenCalledWith({
            message: ENTER_PASS,
            mask: true,
            theme: {
                prefix: '>',
            },
        });
    });

    it('should handle errors from the password prompt', async () => {
        (password as jest.Mock).mockRejectedValue(new Error('Prompt failed'));

        await expect(passwordPrompt(undefined)).rejects.toThrow('Prompt failed');
    });

    it('should not prompt if inputPassword is provided and verify no unnecessary prompts', async () => {
        const providedPassword = 'xyz';
        const result = await passwordPrompt(providedPassword);
        expect(result).toBe(providedPassword);
        expect(password).not.toHaveBeenCalled();
    });

    it('should call password prompt exactly once with correct parameters when inputPassword is not provided', async () => {
        const userInput = 'xyz';
        (password as jest.Mock).mockResolvedValue(userInput);

        await passwordPrompt(undefined);
        expect(password).toHaveBeenCalledTimes(1);
        expect(password).toHaveBeenCalledWith({
            message: ENTER_PASS,
            mask: true,
            theme: {
                prefix: '>',
            },
        });
    });
});
