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 { handleGitPush } from "../git-push.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_push handler", () => {
    let tempDir;
    let remoteDir;
    let projectDir;
    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-push-test-"));
        tempDir = await realpath(rawTempDir);
        remoteDir = join(tempDir, "remote.git");
        projectDir = join(tempDir, "project");
        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"); // Ensure branch is named "master" (after first commit)
        await git(projectDir, "remote", "add", "origin", remoteDir);
        await git(projectDir, "push", "-u", "origin", "master");
        closeDatabase();
        openDatabase(dbPath);
        const project = createProject("test-project", projectDir);
        projectId = project.project_id;
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createPushRequest(payload = {}) {
        return {
            type: "git_push",
            requestId: "req-1",
            sessionId: projectId,
            payload,
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should push to origin", async () => {
        // Create a new commit to push
        await writeFile(join(projectDir, "file1.ts"), "export const a = 1;");
        await git(projectDir, "add", "file1.ts");
        await git(projectDir, "commit", "-m", "add file1");
        const { responses, send } = createSendCollector();
        await handleGitPush(createPushRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_push_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.remote).toBe("origin");
        expect(resp.payload.branch).toBe("master");
        expect(resp.payload.pushed).toBe(true);
        // Verify the remote has the commit
        const remoteLog = await git(remoteDir, "log", "--oneline");
        expect(remoteLog).toContain("add file1");
    });
    it("should push specific branch", async () => {
        // Create a new branch with a commit
        await git(projectDir, "checkout", "-b", "feature-branch");
        await writeFile(join(projectDir, "feature.ts"), "export const f = 1;");
        await git(projectDir, "add", "feature.ts");
        await git(projectDir, "commit", "-m", "add feature");
        const { responses, send } = createSendCollector();
        await handleGitPush(createPushRequest({ branch: "feature-branch" }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.branch).toBe("feature-branch");
        expect(resp.payload.pushed).toBe(true);
    });
    it("should handle push rejection with parsed error", async () => {
        // Create a commit on the remote directly to cause conflict
        const otherDir = join(tempDir, "other");
        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");
        await writeFile(join(otherDir, "other.ts"), "export const o = 1;");
        await git(otherDir, "add", "other.ts");
        await git(otherDir, "commit", "-m", "other commit");
        await git(otherDir, "push", "origin", "master");
        // Now try to push from our project (which is behind)
        await writeFile(join(projectDir, "local.ts"), "export const l = 1;");
        await git(projectDir, "add", "local.ts");
        await git(projectDir, "commit", "-m", "local commit");
        const { responses, send } = createSendCollector();
        await handleGitPush(createPushRequest(), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNKNOWN_ERROR);
        // Error should include parsed details
        expect(resp.error.details).toBeDefined();
    });
    it("should error for non-existent project", async () => {
        const msg = {
            type: "git_push",
            requestId: "req-2",
            sessionId: "non-existent-project",
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitPush(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_push",
            requestId: "req-3",
            sessionId: project.project_id,
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitPush(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 gitPush for credential support", async () => {
        // Create a commit to push
        await writeFile(join(projectDir, "cred-test.ts"), "export const c = 1;");
        await git(projectDir, "add", "cred-test.ts");
        await git(projectDir, "commit", "-m", "credential test");
        const { responses, send } = createSendCollector();
        const request = createPushRequest();
        await handleGitPush(request, send);
        expect(responses).toHaveLength(1);
        // Should succeed (local push, no credentials needed)
        expect(responses[0].error).toBeUndefined();
        expect(responses[0].payload.pushed).toBe(true);
    });
});
//# sourceMappingURL=git-push.test.js.map