import { mkdtemp, rm, mkdir, readFile, writeFile, 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 { MAX_WRITE_SIZE } from "@pocketcoder/shared/constants";
import { openDatabase, closeDatabase } from "../../db/database.js";
import { createProject } from "../../db/repositories/projects.js";
import { handleFsWrite } from "../fs-write.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_write handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-fs-write-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 createFsWriteRequest(path, content, createDirs) {
        return {
            type: "fs_write",
            requestId: "req-1",
            sessionId: projectId,
            payload: { path, content, createDirs },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should write file content", async () => {
        const content = 'export const hello = "world";\n';
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("hello.ts", content), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("fs_write_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("hello.ts");
        expect(resp.payload.size).toBe(Buffer.byteLength(content, "utf-8"));
        expect(resp.payload.mtime).toBeDefined();
        // Verify file was actually written
        const written = await readFile(join(projectDir, "hello.ts"), "utf-8");
        expect(written).toBe(content);
    });
    it("should create parent directories", async () => {
        const content = "const x = 1;\n";
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("src/components/Button.tsx", content, true), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("src/components/Button.tsx");
        // Verify file was written in nested directory
        const written = await readFile(join(projectDir, "src", "components", "Button.tsx"), "utf-8");
        expect(written).toBe(content);
    });
    it("should return file metadata", async () => {
        const content = "Hello World\n";
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("test.txt", content), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        expect(resp.payload.size).toBe(Buffer.byteLength(content, "utf-8"));
        // mtime should be an ISO 8601 string
        expect(new Date(resp.payload.mtime).toISOString()).toBe(resp.payload.mtime);
    });
    it("should error for large content", async () => {
        const largeContent = "x".repeat(MAX_WRITE_SIZE + 1);
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("large.txt", largeContent), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.FILE_TOO_LARGE);
        expect(resp.error.details).toBeDefined();
        expect(resp.error.details.limit).toBe(MAX_WRITE_SIZE);
    });
    it("should prevent path traversal", async () => {
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("../../../tmp/evil.txt", "malicious content"), 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 () => {
        // Create a directory outside the project
        const outsideDir = join(tempDir, "outside");
        await mkdir(outsideDir);
        // Create a symlink inside the project pointing to the outside directory
        await symlink(outsideDir, join(projectDir, "escape-link"));
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("escape-link/evil.txt", "malicious content"), 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_write",
            requestId: "req-2",
            sessionId: "non-existent-project-id",
            payload: { path: "file.txt", content: "hello" },
        };
        const { responses, send } = createSendCollector();
        await handleFsWrite(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should overwrite existing files", async () => {
        await writeFile(join(projectDir, "existing.txt"), "old content");
        const newContent = "new content\n";
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("existing.txt", newContent), send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeUndefined();
        const written = await readFile(join(projectDir, "existing.txt"), "utf-8");
        expect(written).toBe(newContent);
    });
    it("should write empty files", async () => {
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("empty.txt", ""), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.size).toBe(0);
        const written = await readFile(join(projectDir, "empty.txt"), "utf-8");
        expect(written).toBe("");
    });
    it("should write files with UTF-8 content", async () => {
        const unicodeContent = "Hello 世界! 🌍 café résumé naïve";
        const { responses, send } = createSendCollector();
        await handleFsWrite(createFsWriteRequest("unicode.txt", unicodeContent), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.size).toBe(Buffer.byteLength(unicodeContent, "utf-8"));
        const written = await readFile(join(projectDir, "unicode.txt"), "utf-8");
        expect(written).toBe(unicodeContent);
    });
});
//# sourceMappingURL=fs-write.test.js.map