import { mkdtemp, rm, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { ErrorCode } from "@pocketcoder/shared/constants";
import { openDatabase, closeDatabase } from "../../db/database.js";
import { createProject } from "../../db/repositories/projects.js";
import { handleCommandExec } from "../command-exec.js";
import { handleCommandCancel } from "../command-cancel.js";
// Suppress logger output in tests
vi.mock("../../utils/logger.js", () => ({
    logger: {
        debug: vi.fn(),
        info: vi.fn(),
        warn: vi.fn(),
        error: vi.fn(),
    },
}));
describe("command_cancel handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-cmd-cancel-test-"));
        projectDir = join(tempDir, "project");
        dbPath = join(tempDir, "daemon.db");
        await mkdir(projectDir);
        closeDatabase();
        openDatabase(dbPath);
        const project = createProject("test-project", projectDir);
        projectId = project.project_id;
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createSendCollector() {
        const messages = [];
        const send = (msg) => {
            messages.push(msg);
        };
        return { messages, send };
    }
    it("should kill running command", { timeout: 15000 }, async () => {
        const execCollector = createSendCollector();
        const commandRequestId = "req-long-cmd";
        // Use a trap-based approach so SIGTERM is handled cleanly by the shell
        const execRequest = {
            type: "command_exec",
            requestId: commandRequestId,
            sessionId: projectId,
            payload: { command: "exec sleep 30" },
        };
        // Start exec but don't await it
        const execPromise = handleCommandExec(execRequest, execCollector.send);
        // Give command time to start
        await new Promise((r) => setTimeout(r, 500));
        // Cancel the command
        const cancelCollector = createSendCollector();
        const cancelRequest = {
            type: "command_cancel",
            requestId: "req-cancel-1",
            sessionId: projectId,
            payload: { requestId: commandRequestId },
        };
        await handleCommandCancel(cancelRequest, cancelCollector.send);
        // No error should be sent (command was found and killed)
        const cancelErrors = cancelCollector.messages.filter((m) => m.type === "error");
        expect(cancelErrors).toHaveLength(0);
        // Wait for the exec handler to complete
        await execPromise;
        // The exec handler should have sent a command_exit event
        const exitEvents = execCollector.messages.filter((m) => m.type === "command_exit");
        expect(exitEvents).toHaveLength(1);
        expect(exitEvents[0].requestId).toBe(commandRequestId);
    });
    it("should send exit event with SIGTERM", { timeout: 15000 }, async () => {
        const execCollector = createSendCollector();
        const commandRequestId = "req-sigterm-cmd";
        // `exec` replaces the shell, so SIGTERM goes directly to sleep
        const execRequest = {
            type: "command_exec",
            requestId: commandRequestId,
            sessionId: projectId,
            payload: { command: "exec sleep 30" },
        };
        const execPromise = handleCommandExec(execRequest, execCollector.send);
        // Give command time to start
        await new Promise((r) => setTimeout(r, 500));
        // Cancel it
        const cancelCollector = createSendCollector();
        await handleCommandCancel({
            type: "command_cancel",
            requestId: "req-cancel-2",
            sessionId: projectId,
            payload: { requestId: commandRequestId },
        }, cancelCollector.send);
        await execPromise;
        const exitEvents = execCollector.messages.filter((m) => m.type === "command_exit");
        expect(exitEvents).toHaveLength(1);
        expect(exitEvents[0].payload.signal).toBe("SIGTERM");
        expect(exitEvents[0].payload.exitCode).toBeNull();
    });
    it("should handle non-existent command", async () => {
        const cancelCollector = createSendCollector();
        await handleCommandCancel({
            type: "command_cancel",
            requestId: "req-cancel-3",
            sessionId: projectId,
            payload: { requestId: "non-existent-request-id" },
        }, cancelCollector.send);
        // Should send an error response
        expect(cancelCollector.messages).toHaveLength(1);
        const errMsg = cancelCollector.messages[0];
        expect(errMsg.type).toBe("error");
        expect(errMsg.error?.code).toBe(ErrorCode.INVALID_REQUEST);
        expect(errMsg.error?.message).toContain("No running command found");
    });
});
//# sourceMappingURL=command-cancel.test.js.map