import { describe, it, expect, beforeEach, vi } from "vitest";
import { ErrorCode } from "@pocketcoder/shared/constants";
import { handleMachinesList, setMachinesListGatewayClient } from "../machines-list.js";
// Suppress logger output in tests
vi.mock("../../utils/logger.js", () => ({
    logger: {
        debug: vi.fn(),
        info: vi.fn(),
        warn: vi.fn(),
        error: vi.fn(),
    },
}));
// Mock the gateway request utility
vi.mock("../../gateway/gateway-request.js", () => ({
    gatewayRequest: vi.fn(),
}));
import { gatewayRequest } from "../../gateway/gateway-request.js";
const mockGatewayRequest = vi.mocked(gatewayRequest);
// Create a mock gateway client
function createMockGatewayClient(connected = true) {
    return {
        connected,
        send: vi.fn(),
        on: vi.fn(),
        off: vi.fn(),
        connect: vi.fn(),
        disconnect: vi.fn(),
        state: connected ? "connected" : "disconnected",
    };
}
describe("machines_list handler", () => {
    const sampleMachines = [
        {
            machineKey: "machine-key-1",
            label: "Work Laptop",
            os: "darwin",
            osVersion: "macOS 14.2",
            username: "alice",
            online: true,
            lastSeen: "2026-02-14T10:00:00Z",
            projectCount: 3,
        },
        {
            machineKey: "machine-key-2",
            label: "Home Desktop",
            os: "linux",
            osVersion: "Ubuntu 24.04",
            username: "alice",
            online: false,
            lastSeen: "2026-02-13T18:00:00Z",
            projectCount: 1,
        },
    ];
    beforeEach(() => {
        vi.clearAllMocks();
    });
    function createRequest(requestId = "req-1") {
        return {
            type: "machines_list",
            requestId,
            payload: {},
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should forward request to gateway", async () => {
        const mockClient = createMockGatewayClient(true);
        setMachinesListGatewayClient(mockClient);
        mockGatewayRequest.mockResolvedValue({
            type: "machines_list_response",
            requestId: "req-1",
            payload: { machines: sampleMachines },
        });
        const { send } = createSendCollector();
        await handleMachinesList(createRequest(), send);
        expect(mockGatewayRequest).toHaveBeenCalledWith(mockClient, expect.objectContaining({
            type: "machines_list",
            requestId: "req-1",
            payload: {},
        }), "machines_list_response");
    });
    it("should return machine list from gateway response", async () => {
        const mockClient = createMockGatewayClient(true);
        setMachinesListGatewayClient(mockClient);
        const gatewayResponse = {
            type: "machines_list_response",
            requestId: "req-1",
            payload: { machines: sampleMachines },
        };
        mockGatewayRequest.mockResolvedValue(gatewayResponse);
        const { responses, send } = createSendCollector();
        await handleMachinesList(createRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("machines_list_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.machines).toHaveLength(2);
        expect(resp.payload.machines[0]).toEqual(sampleMachines[0]);
        expect(resp.payload.machines[1]).toEqual(sampleMachines[1]);
    });
    it("should error when not connected to gateway", async () => {
        const mockClient = createMockGatewayClient(false);
        setMachinesListGatewayClient(mockClient);
        const { responses, send } = createSendCollector();
        await handleMachinesList(createRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("machines_list_response");
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNKNOWN_ERROR);
        expect(resp.error.message).toBe("Not connected to gateway");
        expect(mockGatewayRequest).not.toHaveBeenCalled();
    });
    it("should error when gateway client is not set", async () => {
        // Reset gateway client to null
        setMachinesListGatewayClient(null);
        const { responses, send } = createSendCollector();
        await handleMachinesList(createRequest(), send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.UNKNOWN_ERROR);
    });
    it("should handle gateway request timeout", async () => {
        const mockClient = createMockGatewayClient(true);
        setMachinesListGatewayClient(mockClient);
        mockGatewayRequest.mockRejectedValue(new Error("Gateway request timed out after 15000ms"));
        const { responses, send } = createSendCollector();
        await handleMachinesList(createRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("machines_list_response");
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNKNOWN_ERROR);
        expect(resp.error.message).toContain("timed out");
    });
    it("should forward gateway error responses", async () => {
        const mockClient = createMockGatewayClient(true);
        setMachinesListGatewayClient(mockClient);
        const gatewayResponse = {
            type: "machines_list_response",
            requestId: "req-1",
            error: {
                code: ErrorCode.UNAUTHORIZED,
                message: "Authentication required",
            },
        };
        mockGatewayRequest.mockResolvedValue(gatewayResponse);
        const { responses, send } = createSendCollector();
        await handleMachinesList(createRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("machines_list_response");
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNAUTHORIZED);
    });
});
//# sourceMappingURL=machines-list.test.js.map