import { mkdtemp, rm, mkdir, writeFile, 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 { handleFsList } from "../fs-list.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_list 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-list-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 createFsListRequest(path, depth) {
        return {
            type: "fs_list",
            requestId: "req-1",
            sessionId: projectId,
            payload: { path, depth },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should list root directory", async () => {
        await writeFile(join(projectDir, "index.ts"), "console.log('hello')");
        await mkdir(join(projectDir, "src"));
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest(""), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("fs_list_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("");
        const names = resp.payload.children.map((c) => c.name);
        expect(names).toContain("index.ts");
        expect(names).toContain("src");
    });
    it("should list subdirectory", async () => {
        await mkdir(join(projectDir, "src"));
        await writeFile(join(projectDir, "src", "app.ts"), "export {}");
        await writeFile(join(projectDir, "src", "utils.ts"), "export {}");
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest("src"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("src");
        const names = resp.payload.children.map((c) => c.name);
        expect(names).toContain("app.ts");
        expect(names).toContain("utils.ts");
    });
    it("should include file metadata", async () => {
        await writeFile(join(projectDir, "readme.md"), "# Hello World");
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest(""), send);
        const file = responses[0].payload.children.find((c) => c.name === "readme.md");
        expect(file).toBeDefined();
        expect(file.type).toBe("file");
        expect(file.size).toBeGreaterThan(0);
        expect(file.mtime).toBeDefined();
        expect(file.path).toBe("readme.md");
    });
    it("should include directory metadata", async () => {
        await mkdir(join(projectDir, "lib"));
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest(""), send);
        const dir = responses[0].payload.children.find((c) => c.name === "lib");
        expect(dir).toBeDefined();
        expect(dir.type).toBe("dir");
        expect(dir.mtime).toBeDefined();
        expect(dir.path).toBe("lib");
    });
    it("should respect depth parameter", async () => {
        await mkdir(join(projectDir, "a"));
        await mkdir(join(projectDir, "a", "b"));
        await writeFile(join(projectDir, "a", "file.txt"), "hello");
        await writeFile(join(projectDir, "a", "b", "nested.txt"), "nested");
        // depth=1 should not expand children
        const c1 = createSendCollector();
        await handleFsList(createFsListRequest("", 1), c1.send);
        const dirA1 = c1.responses[0].payload.children.find((c) => c.name === "a");
        expect(dirA1).toBeDefined();
        expect(dirA1.children).toBeUndefined();
        // depth=2 should expand one level of children
        const c2 = createSendCollector();
        await handleFsList(createFsListRequest("", 2), c2.send);
        const dirA2 = c2.responses[0].payload.children.find((c) => c.name === "a");
        expect(dirA2).toBeDefined();
        expect(dirA2.children).toBeDefined();
        expect(dirA2.expanded).toBe(true);
        const childNames = dirA2.children.map((c) => c.name);
        expect(childNames).toContain("b");
        expect(childNames).toContain("file.txt");
        // depth=2 should not expand the nested "b" directory
        const dirB = dirA2.children.find((c) => c.name === "b");
        expect(dirB.children).toBeUndefined();
    });
    it("should reject paths outside project", async () => {
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest("../../../etc"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.OUTSIDE_PROJECT_ROOT);
    });
    it("should reject symlink escape", async () => {
        // Create a symlink that points outside the project
        const outsideDir = join(tempDir, "outside");
        await mkdir(outsideDir);
        await writeFile(join(outsideDir, "secret.txt"), "secret");
        await symlink(outsideDir, join(projectDir, "escape-link"));
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest("escape-link"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.OUTSIDE_PROJECT_ROOT);
    });
    it("should truncate at 10000 entries", async () => {
        // Create many files to exceed the limit
        const manyDir = join(projectDir, "many");
        await mkdir(manyDir);
        // Create 10001 files
        const promises = [];
        for (let i = 0; i < 10001; i++) {
            promises.push(writeFile(join(manyDir, `file-${String(i).padStart(5, "0")}.txt`), `${i}`));
        }
        await Promise.all(promises);
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest("many"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        expect(resp.payload.children.length).toBeLessThanOrEqual(10000);
    }, 30000);
    it("should return seq from database", async () => {
        await writeFile(join(projectDir, "test.txt"), "test");
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest(""), send);
        expect(responses[0].payload.seq).toBe(0); // No seq incremented yet
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "fs_list",
            requestId: "req-2",
            sessionId: "non-existent-project-id",
            payload: { path: "" },
        };
        const { responses, send } = createSendCollector();
        await handleFsList(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should sort directories before files", async () => {
        await writeFile(join(projectDir, "zebra.txt"), "z");
        await mkdir(join(projectDir, "alpha-dir"));
        await writeFile(join(projectDir, "apple.txt"), "a");
        await mkdir(join(projectDir, "beta-dir"));
        const { responses, send } = createSendCollector();
        await handleFsList(createFsListRequest(""), send);
        const children = responses[0].payload.children;
        const dirIndices = children.map((c, i) => (c.type === "dir" ? i : -1)).filter((i) => i >= 0);
        const fileIndices = children.map((c, i) => (c.type === "file" ? i : -1)).filter((i) => i >= 0);
        // All directories should come before all files
        const maxDirIndex = Math.max(...dirIndices);
        const minFileIndex = Math.min(...fileIndices);
        expect(maxDirIndex).toBeLessThan(minFileIndex);
    });
});
//# sourceMappingURL=fs-list.test.js.map