/**
 * Handler for git_pull messages.
 * Pulls commits from a remote repository via PTY with credential prompt support.
 * Detects merge conflicts and returns conflict file list.
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { getProject } from "../db/repositories/projects.js";
import { gitPull, GitNotInitializedError } from "../services/git.js";
import { parseGitError } from "./git/error-parser.js";
import { logger } from "../utils/logger.js";
export async function handleGitPull(message, send) {
    const msg = message;
    const { requestId, sessionId } = msg;
    const project = getProject(sessionId);
    if (!project) {
        send({
            type: "git_pull_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: `Project not found: ${sessionId}`,
            },
        });
        return;
    }
    try {
        const { remote, branch } = msg.payload;
        const result = await gitPull(project.path, remote, branch, requestId, send);
        send({
            type: "git_pull_response",
            requestId,
            payload: {
                remote: result.remote,
                branch: result.branch,
                pulled: result.pulled,
                ...(result.conflicts ? { conflicts: result.conflicts } : {}),
            },
        });
    }
    catch (err) {
        if (err instanceof GitNotInitializedError) {
            send({
                type: "git_pull_response",
                requestId,
                error: {
                    code: ErrorCode.GIT_NOT_INITIALIZED,
                    message: "Not a git repository",
                },
            });
            return;
        }
        const errorMessage = err instanceof Error ? err.message : String(err);
        const parsed = parseGitError(errorMessage);
        logger.error(`git_pull error: ${errorMessage}`);
        send({
            type: "git_pull_response",
            requestId,
            error: {
                code: ErrorCode.UNKNOWN_ERROR,
                message: parsed.message,
                details: {
                    type: parsed.type,
                    ...(parsed.hint ? { hint: parsed.hint } : {}),
                },
            },
        });
    }
}
//# sourceMappingURL=git-pull.js.map