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 { handleGitDiff } from "../git-diff.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_diff handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-diff-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 createRequest(opts) {
        return {
            type: "git_diff",
            requestId: "req-1",
            sessionId: projectId,
            payload: opts,
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should return diff for modified file", async () => {
        await writeFile(join(projectDir, "README.md"), "# Modified\n");
        const { responses, send } = createSendCollector();
        await handleGitDiff(createRequest({}), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_diff_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.files).toHaveLength(1);
        expect(resp.payload.files[0].path).toBe("README.md");
        expect(resp.payload.files[0].status).toBe("modified");
        expect(resp.payload.files[0].diff).toContain("diff --git");
    });
    it("should handle staged diff", async () => {
        await writeFile(join(projectDir, "README.md"), "# Staged change\n");
        await git(projectDir, "add", "README.md");
        const { responses, send } = createSendCollector();
        await handleGitDiff(createRequest({ staged: true }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.files).toHaveLength(1);
        expect(resp.payload.files[0].path).toBe("README.md");
        expect(resp.payload.files[0].status).toBe("modified");
    });
    it("should count additions and deletions", async () => {
        await writeFile(join(projectDir, "README.md"), "Line 1\nLine 2\nLine 3\n");
        const { responses, send } = createSendCollector();
        await handleGitDiff(createRequest({}), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        const file = resp.payload.files[0];
        expect(file.additions).toBeGreaterThan(0);
        expect(file.deletions).toBeGreaterThan(0);
    });
    it("should handle new files", async () => {
        await writeFile(join(projectDir, "new-file.txt"), "new content\n");
        await git(projectDir, "add", "new-file.txt");
        const { responses, send } = createSendCollector();
        await handleGitDiff(createRequest({ staged: true }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.files).toHaveLength(1);
        expect(resp.payload.files[0].path).toBe("new-file.txt");
        expect(resp.payload.files[0].status).toBe("added");
        expect(resp.payload.files[0].additions).toBeGreaterThan(0);
    });
    it("should diff specific file path", async () => {
        await writeFile(join(projectDir, "README.md"), "# Modified\n");
        await writeFile(join(projectDir, "other.txt"), "other\n");
        await git(projectDir, "add", "other.txt");
        const { responses, send } = createSendCollector();
        await handleGitDiff(createRequest({ path: "README.md" }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.files).toHaveLength(1);
        expect(resp.payload.files[0].path).toBe("README.md");
    });
    it("should return empty files for clean working directory", async () => {
        const { responses, send } = createSendCollector();
        await handleGitDiff(createRequest({}), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.files).toHaveLength(0);
    });
    it("should error for non-git directory", async () => {
        const nonGitDir = join(tempDir, "not-a-repo");
        await mkdir(nonGitDir);
        closeDatabase();
        openDatabase(dbPath);
        const nonGitProject = createProject("non-git-project", nonGitDir);
        const msg = {
            type: "git_diff",
            requestId: "req-2",
            sessionId: nonGitProject.project_id,
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitDiff(msg, send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.GIT_NOT_INITIALIZED);
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "git_diff",
            requestId: "req-3",
            sessionId: "non-existent-project-id",
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitDiff(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should handle deleted files", async () => {
        // Delete a tracked file
        await git(projectDir, "rm", "README.md");
        const { responses, send } = createSendCollector();
        await handleGitDiff(createRequest({ staged: true }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.files).toHaveLength(1);
        expect(resp.payload.files[0].path).toBe("README.md");
        expect(resp.payload.files[0].status).toBe("deleted");
        expect(resp.payload.files[0].deletions).toBeGreaterThan(0);
    });
});
//# sourceMappingURL=git-diff.test.js.map