import { mkdtemp, rm, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
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 { handleGitStage } from "../git-stage.js";
import { handleGitUnstage } from "../git-unstage.js";
const execFileAsync = promisify(execFile);
// Suppress logger output in tests
vi.mock("../../utils/logger.js", () => ({
    logger: {
        debug: vi.fn(),
        info: vi.fn(),
        warn: vi.fn(),
        error: vi.fn(),
    },
}));
async function git(cwd, ...args) {
    const { stdout } = await execFileAsync("git", args, { cwd });
    return stdout.trim();
}
describe("git_stage handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-stage-test-"));
        projectDir = join(tempDir, "project");
        dbPath = join(tempDir, "daemon.db");
        await mkdir(projectDir);
        // Initialize a git repo with initial commit
        await git(projectDir, "init");
        await git(projectDir, "config", "user.email", "test@test.com");
        await git(projectDir, "config", "user.name", "Test User");
        await writeFile(join(projectDir, "README.md"), "# Test\n");
        await git(projectDir, "add", ".");
        await git(projectDir, "commit", "-m", "initial commit");
        closeDatabase();
        openDatabase(dbPath);
        const project = createProject("test-project", projectDir);
        projectId = project.project_id;
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createStageRequest(paths) {
        return {
            type: "git_stage",
            requestId: "req-1",
            sessionId: projectId,
            payload: { paths },
        };
    }
    function createUnstageRequest(paths) {
        return {
            type: "git_unstage",
            requestId: "req-1",
            sessionId: projectId,
            payload: { paths },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should stage specific files", async () => {
        // Create unstaged files
        await writeFile(join(projectDir, "file1.ts"), "export const a = 1;");
        await writeFile(join(projectDir, "file2.ts"), "export const b = 2;");
        const { responses, send } = createSendCollector();
        await handleGitStage(createStageRequest(["file1.ts"]), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_stage_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.staged).toContain("file1.ts");
        // Verify file1 is staged via git
        const staged = await git(projectDir, "diff", "--cached", "--name-only");
        expect(staged).toContain("file1.ts");
        expect(staged).not.toContain("file2.ts");
    });
    it("should stage all files with dot", async () => {
        // Create multiple unstaged files
        await writeFile(join(projectDir, "a.ts"), "a");
        await writeFile(join(projectDir, "b.ts"), "b");
        await writeFile(join(projectDir, "c.ts"), "c");
        const { responses, send } = createSendCollector();
        await handleGitStage(createStageRequest(["."]), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.staged).toContain("a.ts");
        expect(resp.payload.staged).toContain("b.ts");
        expect(resp.payload.staged).toContain("c.ts");
    });
    it("should unstage specific files", async () => {
        // Create and stage files
        await writeFile(join(projectDir, "staged1.ts"), "1");
        await writeFile(join(projectDir, "staged2.ts"), "2");
        await git(projectDir, "add", "staged1.ts", "staged2.ts");
        const { responses, send } = createSendCollector();
        await handleGitUnstage(createUnstageRequest(["staged1.ts"]), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_unstage_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.unstaged).toContain("staged1.ts");
        // Verify staged1 is no longer staged
        const stillStaged = await git(projectDir, "diff", "--cached", "--name-only");
        expect(stillStaged).not.toContain("staged1.ts");
        expect(stillStaged).toContain("staged2.ts");
    });
    it("should unstage all files with dot", async () => {
        // Create and stage files
        await writeFile(join(projectDir, "x.ts"), "x");
        await writeFile(join(projectDir, "y.ts"), "y");
        await git(projectDir, "add", ".");
        const { responses, send } = createSendCollector();
        await handleGitUnstage(createUnstageRequest(["."]), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        // Verify nothing is staged
        const staged = await git(projectDir, "diff", "--cached", "--name-only");
        expect(staged).toBe("");
    });
    it("should error for non-existent project on stage", async () => {
        const msg = {
            type: "git_stage",
            requestId: "req-2",
            sessionId: "non-existent-project",
            payload: { paths: ["file.ts"] },
        };
        const { responses, send } = createSendCollector();
        await handleGitStage(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should error for non-existent project on unstage", async () => {
        const msg = {
            type: "git_unstage",
            requestId: "req-2",
            sessionId: "non-existent-project",
            payload: { paths: ["file.ts"] },
        };
        const { responses, send } = createSendCollector();
        await handleGitUnstage(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
});
//# sourceMappingURL=git-stage.test.js.map