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 { handleGitBranchCreate } from "../git-branch-create.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_branch_create handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-branch-create-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(name, startPoint) {
        return {
            type: "git_branch_create",
            requestId: "req-1",
            sessionId: projectId,
            payload: {
                name,
                ...(startPoint !== undefined ? { startPoint } : {}),
            },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should create branch from HEAD", async () => {
        const { responses, send } = createSendCollector();
        await handleGitBranchCreate(createRequest("feature-a"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_branch_create_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.name).toBe("feature-a");
        expect(resp.payload.created).toBe(true);
        // Verify the branch actually exists
        const branches = await git(projectDir, "branch", "--list");
        expect(branches).toContain("feature-a");
    });
    it("should create branch from start point", async () => {
        // Create a second commit
        await writeFile(join(projectDir, "second.txt"), "second\n");
        await git(projectDir, "add", ".");
        await git(projectDir, "commit", "-m", "second commit");
        // Get the first commit hash
        const firstCommit = await git(projectDir, "rev-list", "--max-parents=0", "HEAD");
        const { responses, send } = createSendCollector();
        await handleGitBranchCreate(createRequest("from-first", firstCommit), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.name).toBe("from-first");
        expect(resp.payload.created).toBe(true);
        // Verify the branch points at the first commit
        const branchCommit = await git(projectDir, "rev-parse", "from-first");
        expect(branchCommit).toBe(firstCommit);
    });
    it("should error for invalid branch name", async () => {
        const { responses, send } = createSendCollector();
        // Branch names with spaces are invalid in git
        await handleGitBranchCreate(createRequest("invalid..name"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNKNOWN_ERROR);
    });
    it("should error for duplicate branch name", async () => {
        // Create the branch first
        await git(projectDir, "branch", "existing-branch");
        const { responses, send } = createSendCollector();
        await handleGitBranchCreate(createRequest("existing-branch"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNKNOWN_ERROR);
    });
    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_branch_create",
            requestId: "req-2",
            sessionId: nonGitProject.project_id,
            payload: { name: "feature" },
        };
        const { responses, send } = createSendCollector();
        await handleGitBranchCreate(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_branch_create",
            requestId: "req-3",
            sessionId: "non-existent-project-id",
            payload: { name: "feature" },
        };
        const { responses, send } = createSendCollector();
        await handleGitBranchCreate(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
});
//# sourceMappingURL=git-branch-create.test.js.map