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 { handleGitBranches } from "../git-branches.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_branches handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-branches-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 createGitBranchesRequest() {
        return {
            type: "git_branches",
            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 handleGitBranches(createGitBranchesRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_branches_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.current);
    });
    it("should list all local branches", async () => {
        // Create additional branches
        await git(projectDir, "branch", "feature-a");
        await git(projectDir, "branch", "feature-b");
        const { responses, send } = createSendCollector();
        await handleGitBranches(createGitBranchesRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        const branchNames = resp.payload.branches.map((b) => b.name);
        expect(branchNames).toContain("feature-a");
        expect(branchNames).toContain("feature-b");
        // Should also include the default branch
        expect(branchNames.some((n) => n === "main" || n === "master")).toBe(true);
        expect(resp.payload.branches.length).toBe(3);
    });
    it("should include remote tracking info", async () => {
        // Create a bare remote to set up tracking
        const remoteDir = join(tempDir, "remote.git");
        await git(tempDir, "clone", "--bare", projectDir, remoteDir);
        await git(projectDir, "remote", "add", "origin", remoteDir);
        await git(projectDir, "fetch", "origin");
        // Get the default branch name
        const defaultBranch = await git(projectDir, "rev-parse", "--abbrev-ref", "HEAD");
        // Set upstream tracking
        await git(projectDir, "branch", `--set-upstream-to=origin/${defaultBranch}`, defaultBranch);
        const { responses, send } = createSendCollector();
        await handleGitBranches(createGitBranchesRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        const trackedBranch = resp.payload.branches.find((b) => b.name === defaultBranch);
        expect(trackedBranch).toBeDefined();
        expect(trackedBranch.remote).toBe(`origin/${defaultBranch}`);
    });
    it("should include ahead/behind counts", async () => {
        // Create a bare remote
        const remoteDir = join(tempDir, "remote.git");
        await git(tempDir, "clone", "--bare", projectDir, remoteDir);
        await git(projectDir, "remote", "add", "origin", remoteDir);
        await git(projectDir, "fetch", "origin");
        const defaultBranch = await git(projectDir, "rev-parse", "--abbrev-ref", "HEAD");
        await git(projectDir, "branch", `--set-upstream-to=origin/${defaultBranch}`, defaultBranch);
        // Make a local commit to be ahead of remote
        await writeFile(join(projectDir, "new-file.txt"), "new content\n");
        await git(projectDir, "add", ".");
        await git(projectDir, "commit", "-m", "local commit");
        const { responses, send } = createSendCollector();
        await handleGitBranches(createGitBranchesRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        const trackedBranch = resp.payload.branches.find((b) => b.name === defaultBranch);
        expect(trackedBranch).toBeDefined();
        expect(trackedBranch.ahead).toBe(1);
        expect(trackedBranch.behind).toBe(0);
    });
    it("should show null remote for untracked branches", async () => {
        // Create a branch without remote tracking
        await git(projectDir, "branch", "local-only");
        const { responses, send } = createSendCollector();
        await handleGitBranches(createGitBranchesRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        const localBranch = resp.payload.branches.find((b) => b.name === "local-only");
        expect(localBranch).toBeDefined();
        expect(localBranch.remote).toBeNull();
        expect(localBranch.ahead).toBe(0);
        expect(localBranch.behind).toBe(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_branches",
            requestId: "req-2",
            sessionId: nonGitProject.project_id,
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitBranches(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_branches",
            requestId: "req-3",
            sessionId: "non-existent-project-id",
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitBranches(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
});
//# sourceMappingURL=git-branches.test.js.map