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 { handleGitCommit } from "../git-commit.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_commit handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-commit-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 createCommitRequest(message) {
        return {
            type: "git_commit",
            requestId: "req-1",
            sessionId: projectId,
            payload: { message },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should create commit with message", async () => {
        // Stage a new file
        await writeFile(join(projectDir, "file1.ts"), "export const a = 1;");
        await git(projectDir, "add", "file1.ts");
        const { responses, send } = createSendCollector();
        await handleGitCommit(createCommitRequest("feat: add file1"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_commit_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.message).toBe("feat: add file1");
        expect(resp.payload.sha).toMatch(/^[a-f0-9]{40}$/);
    });
    it("should return commit sha", async () => {
        await writeFile(join(projectDir, "file2.ts"), "export const b = 2;");
        await git(projectDir, "add", "file2.ts");
        const { responses, send } = createSendCollector();
        await handleGitCommit(createCommitRequest("add file2"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        // Verify the sha matches the actual HEAD
        const headSha = await git(projectDir, "rev-parse", "HEAD");
        expect(resp.payload.sha).toBe(headSha);
    });
    it("should error when nothing staged", async () => {
        const { responses, send } = createSendCollector();
        await handleGitCommit(createCommitRequest("empty commit"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNKNOWN_ERROR);
    });
    it("should error for non-existent project", async () => {
        const msg = {
            type: "git_commit",
            requestId: "req-2",
            sessionId: "non-existent-project",
            payload: { message: "some commit" },
        };
        const { responses, send } = createSendCollector();
        await handleGitCommit(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-git directory", async () => {
        // Create a project pointing to a non-git directory
        const nonGitDir = join(tempDir, "non-git");
        await mkdir(nonGitDir);
        const project = createProject("non-git-project", nonGitDir);
        const msg = {
            type: "git_commit",
            requestId: "req-3",
            sessionId: project.project_id,
            payload: { message: "test" },
        };
        const { responses, send } = createSendCollector();
        await handleGitCommit(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.GIT_NOT_INITIALIZED);
    });
});
//# sourceMappingURL=git-commit.test.js.map