import { mkdtemp, rm, mkdir, writeFile, stat, symlink, realpath } 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 { handleFsDelete } from "../fs-delete.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("fs_delete handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        // Use realpath to get the canonical path (handles macOS /var -> /private/var symlink)
        const rawTempDir = await mkdtemp(join(tmpdir(), "pocketcoder-fs-delete-test-"));
        tempDir = await realpath(rawTempDir);
        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 createFsDeleteRequest(path) {
        return {
            type: "fs_delete",
            requestId: "req-1",
            sessionId: projectId,
            payload: { path },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should delete file", async () => {
        await writeFile(join(projectDir, "file.txt"), "content");
        const { responses, send } = createSendCollector();
        await handleFsDelete(createFsDeleteRequest("file.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("fs_delete_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("file.txt");
        // Verify file was actually deleted
        await expect(stat(join(projectDir, "file.txt"))).rejects.toThrow();
    });
    it("should delete directory recursively", async () => {
        await mkdir(join(projectDir, "mydir", "subdir"), { recursive: true });
        await writeFile(join(projectDir, "mydir", "subdir", "nested.txt"), "data");
        await writeFile(join(projectDir, "mydir", "top.txt"), "data");
        const { responses, send } = createSendCollector();
        await handleFsDelete(createFsDeleteRequest("mydir"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("mydir");
        // Verify directory was actually deleted
        await expect(stat(join(projectDir, "mydir"))).rejects.toThrow();
    });
    it("should return error if not found", async () => {
        const { responses, send } = createSendCollector();
        await handleFsDelete(createFsDeleteRequest("nonexistent.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.FILE_NOT_FOUND);
    });
    it("should prevent path traversal", async () => {
        const { responses, send } = createSendCollector();
        await handleFsDelete(createFsDeleteRequest("../../../tmp/evil.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.OUTSIDE_PROJECT_ROOT);
    });
    it("should prevent symlink escape", async () => {
        const outsideDir = join(tempDir, "outside");
        await mkdir(outsideDir);
        await writeFile(join(outsideDir, "secret.txt"), "sensitive");
        await symlink(outsideDir, join(projectDir, "escape-link"));
        const { responses, send } = createSendCollector();
        await handleFsDelete(createFsDeleteRequest("escape-link/secret.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.OUTSIDE_PROJECT_ROOT);
        // Verify the outside file was NOT deleted
        const stats = await stat(join(outsideDir, "secret.txt"));
        expect(stats.isFile()).toBe(true);
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "fs_delete",
            requestId: "req-2",
            sessionId: "non-existent-project-id",
            payload: { path: "file.txt" },
        };
        const { responses, send } = createSendCollector();
        await handleFsDelete(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should delete empty directory", async () => {
        await mkdir(join(projectDir, "emptydir"));
        const { responses, send } = createSendCollector();
        await handleFsDelete(createFsDeleteRequest("emptydir"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("emptydir");
        await expect(stat(join(projectDir, "emptydir"))).rejects.toThrow();
    });
    it("should delete file in subdirectory", async () => {
        await mkdir(join(projectDir, "sub"));
        await writeFile(join(projectDir, "sub", "file.txt"), "content");
        const { responses, send } = createSendCollector();
        await handleFsDelete(createFsDeleteRequest("sub/file.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.path).toBe("sub/file.txt");
        // Verify file deleted but parent directory still exists
        await expect(stat(join(projectDir, "sub", "file.txt"))).rejects.toThrow();
        const parentStat = await stat(join(projectDir, "sub"));
        expect(parentStat.isDirectory()).toBe(true);
    });
});
//# sourceMappingURL=fs-delete.test.js.map