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 { handleGitCheckout } from "../git-checkout.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_checkout handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-checkout-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");
        // Create a second branch
        await git(projectDir, "branch", "feature-branch");
        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(ref) {
        return {
            type: "git_checkout",
            requestId: "req-1",
            sessionId: projectId,
            payload: { ref },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should checkout existing branch", async () => {
        const { responses, send } = createSendCollector();
        await handleGitCheckout(createRequest("feature-branch"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_checkout_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.ref).toBe("feature-branch");
        expect(resp.payload.switched).toBe(true);
        // Verify we are actually on the branch
        const currentBranch = await git(projectDir, "rev-parse", "--abbrev-ref", "HEAD");
        expect(currentBranch).toBe("feature-branch");
    });
    it("should error for non-existent ref", async () => {
        const { responses, send } = createSendCollector();
        await handleGitCheckout(createRequest("non-existent-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_checkout",
            requestId: "req-2",
            sessionId: nonGitProject.project_id,
            payload: { ref: "main" },
        };
        const { responses, send } = createSendCollector();
        await handleGitCheckout(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_checkout",
            requestId: "req-3",
            sessionId: "non-existent-project-id",
            payload: { ref: "main" },
        };
        const { responses, send } = createSendCollector();
        await handleGitCheckout(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
});
//# sourceMappingURL=git-checkout.test.js.map