import { mkdtemp, rm, mkdir, writeFile } 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 { handleFsSearch, resetRipgrepCache } from "../fs-search.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_search handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-fs-search-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;
        // Reset ripgrep cache so each test starts fresh
        resetRipgrepCache();
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createFsSearchRequest(query, options) {
        return {
            type: "fs_search",
            requestId: "req-1",
            sessionId: projectId,
            payload: {
                query,
                ...options,
            },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should search file contents", async () => {
        await writeFile(join(projectDir, "hello.txt"), "Hello world\nfoo bar\nHello again");
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("Hello"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("fs_search_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.query).toBe("Hello");
        expect(resp.payload.totalMatches).toBe(2);
        expect(resp.payload.truncated).toBe(false);
        expect(resp.payload.files.length).toBeGreaterThanOrEqual(1);
        const file = resp.payload.files.find((f) => f.path === "hello.txt");
        expect(file).toBeDefined();
        expect(file.matches).toHaveLength(2);
        expect(file.matches[0].line).toBe(1);
        expect(file.matches[0].content).toContain("Hello world");
        expect(file.matches[1].line).toBe(3);
    });
    it("should filter by glob pattern", async () => {
        await writeFile(join(projectDir, "app.ts"), "const x = 1;");
        await writeFile(join(projectDir, "app.js"), "const x = 2;");
        await writeFile(join(projectDir, "readme.md"), "const x = 3;");
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("const", { glob: "*.ts" }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.totalMatches).toBe(1);
        expect(resp.payload.files).toHaveLength(1);
        expect(resp.payload.files[0].path).toBe("app.ts");
    });
    it("should handle case sensitivity", async () => {
        await writeFile(join(projectDir, "test.txt"), "Hello\nhello\nHELLO");
        // Case insensitive (default)
        const { responses: r1, send: s1 } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("hello"), s1);
        expect(r1[0].payload.totalMatches).toBe(3);
        // Case sensitive
        const { responses: r2, send: s2 } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("hello", { caseSensitive: true }), s2);
        expect(r2[0].payload.totalMatches).toBe(1);
    });
    it("should support regex", async () => {
        await writeFile(join(projectDir, "code.ts"), "const foo = 1;\nconst bar = 2;\nlet baz = 3;");
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("const \\w+ = \\d+", { regex: true }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.totalMatches).toBe(2);
    });
    it("should limit results", async () => {
        // Create a file with many matches
        const lines = [];
        for (let i = 0; i < 1100; i++) {
            lines.push(`match_target line ${i}`);
        }
        await writeFile(join(projectDir, "big.txt"), lines.join("\n"));
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("match_target"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.totalMatches).toBeLessThanOrEqual(1000);
        expect(resp.payload.truncated).toBe(true);
    });
    it("should exclude node_modules and .git", async () => {
        await mkdir(join(projectDir, "node_modules", "pkg"), { recursive: true });
        await writeFile(join(projectDir, "node_modules", "pkg", "index.js"), "const target = 1;");
        await mkdir(join(projectDir, ".git", "objects"), { recursive: true });
        await writeFile(join(projectDir, ".git", "config"), "const target = 2;");
        await writeFile(join(projectDir, "src.ts"), "const target = 3;");
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("target"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.totalMatches).toBe(1);
        expect(resp.payload.files).toHaveLength(1);
        expect(resp.payload.files[0].path).toBe("src.ts");
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "fs_search",
            requestId: "req-2",
            sessionId: "non-existent-project-id",
            payload: { query: "test" },
        };
        const { responses, send } = createSendCollector();
        await handleFsSearch(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should return error for empty query", async () => {
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest(""), send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.QUERY_TOO_SHORT);
    });
    it("should return error for invalid regex", async () => {
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("[invalid(", { regex: true }), send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REGEX);
    });
    it("should return empty results for no matches", async () => {
        await writeFile(join(projectDir, "file.txt"), "nothing here");
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("nonexistent_query_xyz"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.totalMatches).toBe(0);
        expect(resp.payload.files).toHaveLength(0);
        expect(resp.payload.truncated).toBe(false);
    });
    it("should search in subdirectories", async () => {
        await mkdir(join(projectDir, "src", "utils"), { recursive: true });
        await writeFile(join(projectDir, "src", "utils", "helper.ts"), "export function searchable() {}");
        const { responses, send } = createSendCollector();
        await handleFsSearch(createFsSearchRequest("searchable"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.totalMatches).toBe(1);
        const file = resp.payload.files[0];
        // Path should be relative with forward slashes
        expect(file.path).toContain("src");
        expect(file.path).toContain("helper.ts");
    });
});
//# sourceMappingURL=fs-search.test.js.map