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";
// Suppress logger output in tests
vi.mock("../../utils/logger.js", () => ({
    logger: {
        debug: vi.fn(),
        info: vi.fn(),
        warn: vi.fn(),
        error: vi.fn(),
    },
}));
// Mock node-pty
const mockOnData = vi.fn();
const mockOnExit = vi.fn();
const mockWrite = vi.fn();
const mockResize = vi.fn();
const mockKill = vi.fn();
const mockSpawn = vi.fn().mockReturnValue({
    pid: 12345,
    onData: mockOnData,
    onExit: mockOnExit,
    write: mockWrite,
    resize: mockResize,
    kill: mockKill,
});
vi.mock("node-pty", () => ({
    spawn: (...args) => mockSpawn(...args),
}));
// Mock terminal-sessions DB calls
vi.mock("../../db/repositories/terminal-sessions.js", () => ({
    createTerminalSession: vi.fn().mockReturnValue({
        terminal_id: "mock-terminal-id",
        project_id: "mock-project-id",
        pid: 12345,
        created_at: "2026-02-20T00:00:00.000Z",
        closed_at: null,
    }),
    closeTerminalSession: vi.fn(),
}));
import { handleTerminalKill } from "../terminal-kill.js";
import { createTerminal, setTerminalSendFn } from "../../services/terminal-manager.js";
describe("terminal_kill handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    let terminalId;
    beforeEach(async () => {
        vi.clearAllMocks();
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-terminal-kill-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;
        // Set up terminal send function
        setTerminalSendFn(vi.fn());
        // Create a terminal for testing kill
        terminalId = createTerminal(projectId, projectDir);
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createRequest(overrides) {
        return {
            type: "terminal_kill",
            requestId: "req-1",
            sessionId: projectId,
            payload: {
                terminalId,
                ...overrides,
            },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should kill PTY process", async () => {
        const { responses, send } = createSendCollector();
        await handleTerminalKill(createRequest(), send);
        expect(mockKill).toHaveBeenCalledOnce();
        // No response on success (fire-and-forget)
        expect(responses).toHaveLength(0);
    });
    it("should return error for invalid terminalId", async () => {
        const { responses, send } = createSendCollector();
        await handleTerminalKill(createRequest({ terminalId: "non-existent-terminal" }), send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error.code).toBe(ErrorCode.TERMINAL_NOT_FOUND);
    });
    it("should not send response on successful kill", async () => {
        const { responses, send } = createSendCollector();
        await handleTerminalKill(createRequest(), send);
        expect(responses).toHaveLength(0);
        expect(mockKill).toHaveBeenCalledOnce();
    });
    it("should include requestId in error response", async () => {
        const { responses, send } = createSendCollector();
        const request = createRequest({ terminalId: "bad-id" });
        request.requestId = "req-42";
        await handleTerminalKill(request, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].requestId).toBe("req-42");
    });
    it("should include terminalId in error message", async () => {
        const { responses, send } = createSendCollector();
        await handleTerminalKill(createRequest({ terminalId: "missing-terminal" }), send);
        expect(responses).toHaveLength(1);
        const error = responses[0].error;
        expect(error.message).toContain("missing-terminal");
    });
});
//# sourceMappingURL=terminal-kill.test.js.map