import { mkdtemp, rm, mkdir, writeFile, realpath } 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 { handleGitPull } from "../git-pull.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_pull handler", () => {
    let tempDir;
    let remoteDir;
    let projectDir;
    let otherDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        // Use realpath to get the canonical path (handles macOS /var -> /private/var symlink)
        const rawTempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-pull-test-"));
        tempDir = await realpath(rawTempDir);
        remoteDir = join(tempDir, "remote.git");
        projectDir = join(tempDir, "project");
        otherDir = join(tempDir, "other");
        dbPath = join(tempDir, "daemon.db");
        // Create a bare remote repo with master as default branch
        await mkdir(remoteDir);
        await git(remoteDir, "init", "--bare", "--initial-branch=master");
        // Create a local repo that tracks the bare remote
        await mkdir(projectDir);
        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");
        await git(projectDir, "branch", "-M", "master");
        await git(projectDir, "config", "pull.rebase", "false");
        await git(projectDir, "remote", "add", "origin", remoteDir);
        await git(projectDir, "push", "-u", "origin", "master");
        // Create another clone to push changes that we'll later pull
        await mkdir(otherDir);
        await git(otherDir, "clone", remoteDir, ".");
        await git(otherDir, "config", "user.email", "other@test.com");
        await git(otherDir, "config", "user.name", "Other User");
        closeDatabase();
        openDatabase(dbPath);
        const project = createProject("test-project", projectDir);
        projectId = project.project_id;
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createPullRequest(payload = {}) {
        return {
            type: "git_pull",
            requestId: "req-1",
            sessionId: projectId,
            payload,
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should pull from remote", async () => {
        // Push a new commit from the other clone
        await writeFile(join(otherDir, "new-file.ts"), "export const x = 1;");
        await git(otherDir, "add", "new-file.ts");
        await git(otherDir, "commit", "-m", "add new file");
        await git(otherDir, "push", "origin", "master");
        const { responses, send } = createSendCollector();
        await handleGitPull(createPullRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_pull_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.remote).toBe("origin");
        expect(resp.payload.branch).toBe("master");
        expect(resp.payload.pulled).toBe(true);
        // Verify the local repo has the new commit
        const log = await git(projectDir, "log", "--oneline");
        expect(log).toContain("add new file");
    });
    it("should pull when already up to date", async () => {
        const { responses, send } = createSendCollector();
        await handleGitPull(createPullRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.pulled).toBe(true);
    });
    it("should detect merge conflicts", async () => {
        // Push a change to the remote from another clone
        await writeFile(join(otherDir, "README.md"), "# Changed by other\n");
        await git(otherDir, "add", "README.md");
        await git(otherDir, "commit", "-m", "change readme from other");
        await git(otherDir, "push", "origin", "master");
        // Make a conflicting change locally
        await writeFile(join(projectDir, "README.md"), "# Changed locally\n");
        await git(projectDir, "add", "README.md");
        await git(projectDir, "commit", "-m", "change readme locally");
        const { responses, send } = createSendCollector();
        await handleGitPull(createPullRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        // Should resolve (not error) with conflicts
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.pulled).toBe(false);
        expect(resp.payload.conflicts).toBeDefined();
        expect(resp.payload.conflicts.length).toBeGreaterThan(0);
        // Clean up merge state
        await git(projectDir, "merge", "--abort");
    });
    it("should error for non-existent project", async () => {
        const msg = {
            type: "git_pull",
            requestId: "req-2",
            sessionId: "non-existent-project",
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitPull(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should error for non-git directory", async () => {
        const nonGitDir = join(tempDir, "non-git");
        await mkdir(nonGitDir);
        const project = createProject("non-git-project", nonGitDir);
        const msg = {
            type: "git_pull",
            requestId: "req-3",
            sessionId: project.project_id,
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitPull(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.GIT_NOT_INITIALIZED);
    });
    it("should pass requestId and send to gitPull for credential support", async () => {
        // Push a commit so there's something to pull
        await writeFile(join(otherDir, "cred-test.ts"), "export const c = 1;");
        await git(otherDir, "add", "cred-test.ts");
        await git(otherDir, "commit", "-m", "credential test");
        await git(otherDir, "push", "origin", "master");
        const { responses, send } = createSendCollector();
        const request = createPullRequest();
        await handleGitPull(request, send);
        expect(responses).toHaveLength(1);
        // Should succeed (local pull, no credentials needed)
        expect(responses[0].error).toBeUndefined();
        expect(responses[0].payload.pulled).toBe(true);
    });
});
//# sourceMappingURL=git-pull.test.js.map