"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const opener_1 = __importDefault(require("opener"));
const constants_1 = require("../../src/constants");
const logger_1 = __importDefault(require("../../src/logger"));
const server_1 = require("../../src/util/server");
const server_2 = require("../../src/util/server");
jest.mock('opener');
jest.mock('../../src/logger');
jest.mock('readline');
const mockFetch = jest.fn();
global.fetch = mockFetch;
describe('server utilities', () => {
    let mockReadline;
    beforeEach(() => {
        jest.clearAllMocks();
        mockReadline = {
            question: jest.fn(),
            close: jest.fn(),
        };
        const readline = jest.requireMock('readline');
        readline.createInterface.mockReturnValue(mockReadline);
    });
    describe('checkServerRunning', () => {
        it('returns true when server is running with matching version', async () => {
            mockFetch.mockResolvedValueOnce({
                json: () => Promise.resolve({ status: 'OK', version: constants_1.VERSION }),
            });
            const result = await (0, server_2.checkServerRunning)(constants_1.DEFAULT_PORT);
            expect(result).toBe(true);
            expect(mockFetch).toHaveBeenCalledWith(`http://localhost:${constants_1.DEFAULT_PORT}/health`);
        });
        it('returns false when server returns non-OK status', async () => {
            mockFetch.mockResolvedValueOnce({
                json: () => Promise.resolve({ status: 'ERROR', version: constants_1.VERSION }),
            });
            const result = await (0, server_2.checkServerRunning)();
            expect(result).toBe(false);
        });
        it('returns false when server version does not match', async () => {
            mockFetch.mockResolvedValueOnce({
                json: () => Promise.resolve({ status: 'OK', version: '0.0.0' }),
            });
            const result = await (0, server_2.checkServerRunning)();
            expect(result).toBe(false);
        });
        it('returns false and logs debug message when fetch fails', async () => {
            mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
            const result = await (0, server_2.checkServerRunning)();
            expect(result).toBe(false);
            expect(logger_1.default.debug).toHaveBeenCalledWith(expect.stringContaining('Failed to check server health'));
        });
        it('uses default port when not specified', async () => {
            mockFetch.mockResolvedValueOnce({
                json: () => Promise.resolve({ status: 'OK', version: constants_1.VERSION }),
            });
            await (0, server_2.checkServerRunning)();
            expect(mockFetch).toHaveBeenCalledWith(`http://localhost:${constants_1.DEFAULT_PORT}/health`);
        });
    });
    describe('openBrowser', () => {
        it('opens browser directly with OPEN behavior', async () => {
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.OPEN);
            expect(opener_1.default).toHaveBeenCalledWith(`http://localhost:${constants_1.DEFAULT_PORT}`);
            expect(logger_1.default.info).toHaveBeenCalledWith('Press Ctrl+C to stop the server');
        });
        it('opens report page with OPEN_TO_REPORT behavior', async () => {
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.OPEN_TO_REPORT);
            expect(opener_1.default).toHaveBeenCalledWith(`http://localhost:${constants_1.DEFAULT_PORT}/report`);
        });
        it('opens redteam setup with OPEN_TO_REDTEAM_CREATE behavior', async () => {
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.OPEN_TO_REDTEAM_CREATE);
            expect(opener_1.default).toHaveBeenCalledWith(`http://localhost:${constants_1.DEFAULT_PORT}/redteam/setup`);
        });
        it('does not open browser with SKIP behavior', async () => {
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.SKIP);
            expect(opener_1.default).not.toHaveBeenCalled();
        });
        it('prompts user with ASK behavior and opens on yes', async () => {
            mockReadline.question.mockImplementationOnce((_, callback) => {
                callback('y');
            });
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.ASK);
            expect(mockReadline.question).toHaveBeenCalledWith('Open URL in browser? (y/N): ', expect.any(Function));
            expect(opener_1.default).toHaveBeenCalledWith(`http://localhost:${constants_1.DEFAULT_PORT}`);
            expect(mockReadline.close).toHaveBeenCalledWith();
        });
        it('prompts user with ASK behavior and skips on no', async () => {
            mockReadline.question.mockImplementationOnce((_, callback) => {
                callback('n');
            });
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.ASK);
            expect(mockReadline.question).toHaveBeenCalledWith('Open URL in browser? (y/N): ', expect.any(Function));
            expect(opener_1.default).not.toHaveBeenCalled();
            expect(mockReadline.close).toHaveBeenCalledWith();
        });
        it('handles opener errors gracefully', async () => {
            jest.mocked(opener_1.default).mockImplementation(() => {
                throw new Error('Failed to open browser');
            });
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.OPEN);
            expect(logger_1.default.error).toHaveBeenCalledWith(expect.stringContaining('Failed to open browser'));
        });
        it('uses custom port when specified', async () => {
            const customPort = 3000;
            await (0, server_2.openBrowser)(server_1.BrowserBehavior.OPEN, customPort);
            expect(opener_1.default).toHaveBeenCalledWith(`http://localhost:${customPort}`);
        });
    });
});
//# sourceMappingURL=server.test.js.map