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 { handleGitStatus } from "../git-status.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_status handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-status-test-"));
        projectDir = join(tempDir, "project");
        dbPath = join(tempDir, "daemon.db");
        await mkdir(projectDir);
        // Initialize a git repo
        await git(projectDir, "init");
        await git(projectDir, "config", "user.email", "test@test.com");
        await git(projectDir, "config", "user.name", "Test User");
        // Create initial commit so we have a branch
        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 createGitStatusRequest() {
        return {
            type: "git_status",
            requestId: "req-1",
            sessionId: projectId,
            payload: {},
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should return current branch", async () => {
        const { responses, send } = createSendCollector();
        await handleGitStatus(createGitStatusRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_status_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        // Default branch is main or master depending on git config
        expect(["main", "master"]).toContain(resp.payload.branch);
    });
    it("should list staged files", async () => {
        await writeFile(join(projectDir, "new-file.ts"), "export const x = 1;\n");
        await git(projectDir, "add", "new-file.ts");
        const { responses, send } = createSendCollector();
        await handleGitStatus(createGitStatusRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        expect(resp.payload.staged).toEqual(expect.arrayContaining([expect.objectContaining({ path: "new-file.ts", status: "added" })]));
        expect(resp.payload.clean).toBe(false);
    });
    it("should list unstaged files", async () => {
        // Modify a tracked file without staging
        await writeFile(join(projectDir, "README.md"), "# Updated\n");
        const { responses, send } = createSendCollector();
        await handleGitStatus(createGitStatusRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        expect(resp.payload.unstaged).toEqual(expect.arrayContaining([expect.objectContaining({ path: "README.md", status: "modified" })]));
        expect(resp.payload.clean).toBe(false);
    });
    it("should detect modified files", async () => {
        // Stage a modification
        await writeFile(join(projectDir, "README.md"), "# Modified\n");
        await git(projectDir, "add", "README.md");
        const { responses, send } = createSendCollector();
        await handleGitStatus(createGitStatusRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload.staged).toEqual(expect.arrayContaining([expect.objectContaining({ path: "README.md", status: "modified" })]));
    });
    it("should detect untracked files", async () => {
        await writeFile(join(projectDir, "untracked.txt"), "untracked content\n");
        const { responses, send } = createSendCollector();
        await handleGitStatus(createGitStatusRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload.unstaged).toEqual(expect.arrayContaining([
            expect.objectContaining({ path: "untracked.txt", status: "untracked" }),
        ]));
    });
    it("should report clean status when no changes", async () => {
        const { responses, send } = createSendCollector();
        await handleGitStatus(createGitStatusRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload.clean).toBe(true);
        expect(resp.payload.staged).toEqual([]);
        expect(resp.payload.unstaged).toEqual([]);
        expect(resp.payload.conflicts).toEqual([]);
    });
    it("should error for non-git directory", async () => {
        // Create a non-git directory
        const nonGitDir = join(tempDir, "not-a-repo");
        await mkdir(nonGitDir);
        closeDatabase();
        openDatabase(dbPath);
        const nonGitProject = createProject("non-git-project", nonGitDir);
        const msg = {
            type: "git_status",
            requestId: "req-2",
            sessionId: nonGitProject.project_id,
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitStatus(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_status",
            requestId: "req-3",
            sessionId: "non-existent-project-id",
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitStatus(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should handle both staged and unstaged changes", async () => {
        // Stage a new file
        await writeFile(join(projectDir, "staged.ts"), "export const a = 1;\n");
        await git(projectDir, "add", "staged.ts");
        // Modify an existing file without staging
        await writeFile(join(projectDir, "README.md"), "# Changed\n");
        // Create an untracked file
        await writeFile(join(projectDir, "untracked.txt"), "untracked\n");
        const { responses, send } = createSendCollector();
        await handleGitStatus(createGitStatusRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload.clean).toBe(false);
        expect(resp.payload.staged.length).toBeGreaterThanOrEqual(1);
        expect(resp.payload.unstaged.length).toBeGreaterThanOrEqual(2);
    });
});
//# sourceMappingURL=git-status.test.js.map