import { mkdtemp, rm, mkdir, stat, readFile, symlink } 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 { handleFsCreate } from "../fs-create.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_create handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-fs-create-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 createFsCreateRequest(path, itemType, createDirs) {
        return {
            type: "fs_create",
            requestId: "req-1",
            sessionId: projectId,
            payload: { path, itemType, createDirs },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should create empty file", async () => {
        const { responses, send } = createSendCollector();
        await handleFsCreate(createFsCreateRequest("newfile.txt", "file"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("fs_create_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("newfile.txt");
        expect(resp.payload.itemType).toBe("file");
        // Verify file was actually created and is empty
        const content = await readFile(join(projectDir, "newfile.txt"), "utf-8");
        expect(content).toBe("");
    });
    it("should create directory", async () => {
        const { responses, send } = createSendCollector();
        await handleFsCreate(createFsCreateRequest("newdir", "directory"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("newdir");
        expect(resp.payload.itemType).toBe("directory");
        // Verify directory was actually created
        const stats = await stat(join(projectDir, "newdir"));
        expect(stats.isDirectory()).toBe(true);
    });
    it("should create parent directories", async () => {
        const { responses, send } = createSendCollector();
        await handleFsCreate(createFsCreateRequest("a/b/c/deep.txt", "file"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("a/b/c/deep.txt");
        // Verify file and parent directories were created
        const content = await readFile(join(projectDir, "a", "b", "c", "deep.txt"), "utf-8");
        expect(content).toBe("");
    });
    it("should fail if file already exists", async () => {
        // Create an existing file
        const { writeFile: fsWriteFile } = await import("node:fs/promises");
        await fsWriteFile(join(projectDir, "existing.txt"), "content");
        const { responses, send } = createSendCollector();
        await handleFsCreate(createFsCreateRequest("existing.txt", "file"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.FILE_EXISTS);
    });
    it("should fail if directory already exists", async () => {
        await mkdir(join(projectDir, "existingdir"));
        const { responses, send } = createSendCollector();
        await handleFsCreate(createFsCreateRequest("existingdir", "directory"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.FILE_EXISTS);
    });
    it("should prevent path traversal", async () => {
        const { responses, send } = createSendCollector();
        await handleFsCreate(createFsCreateRequest("../../../tmp/evil.txt", "file"), 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 symlink(outsideDir, join(projectDir, "escape-link"));
        const { responses, send } = createSendCollector();
        await handleFsCreate(createFsCreateRequest("escape-link/evil.txt", "file"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.OUTSIDE_PROJECT_ROOT);
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "fs_create",
            requestId: "req-2",
            sessionId: "non-existent-project-id",
            payload: { path: "file.txt", itemType: "file" },
        };
        const { responses, send } = createSendCollector();
        await handleFsCreate(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
});
//# sourceMappingURL=fs-create.test.js.map