/**
 * Permission reply handler for forwarding permission responses to OpenCode.
 *
 * Validates the reply value (once | always | reject) and proxies the request
 * to OpenCode's POST /permission/:id/reply endpoint.
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { logger } from "../utils/logger.js";
import { createError } from "../errors/index.js";
import { proxyToOpenCode } from "./proxy.js";
const VALID_REPLIES = new Set(["once", "always", "reject"]);
/**
 * Handle a permission_reply message from the client.
 *
 * Validates the reply value and forwards to OpenCode via the HTTP proxy.
 */
export async function handlePermissionReply(message, send) {
    const msg = message;
    const { requestId } = msg;
    const { permissionId, reply } = msg.payload;
    // Validate reply value
    if (!VALID_REPLIES.has(reply)) {
        send({
            type: "permission_reply_response",
            requestId,
            error: createError(ErrorCode.INVALID_REQUEST, `Invalid reply value: ${String(reply)}. Must be one of: once, always, reject`),
        });
        return;
    }
    // Validate permissionId
    if (!permissionId || typeof permissionId !== "string") {
        send({
            type: "permission_reply_response",
            requestId,
            error: createError(ErrorCode.INVALID_REQUEST, "Missing or invalid permissionId"),
        });
        return;
    }
    try {
        const response = await proxyToOpenCode({
            method: "POST",
            path: `/permission/${permissionId}/reply`,
            body: JSON.stringify({ reply }),
        });
        logger.debug(`Permission reply for ${permissionId}: ${reply} → ${response.status}`);
        send({
            type: "permission_reply_response",
            requestId,
            payload: {
                status: response.status,
                body: response.body ? JSON.parse(response.body) : undefined,
            },
        });
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        logger.error(`Permission reply failed for ${permissionId}: ${message}`);
        const code = message === "OPENCODE_UNREACHABLE"
            ? ErrorCode.OPENCODE_UNREACHABLE
            : message === "TIMEOUT"
                ? ErrorCode.TIMEOUT
                : ErrorCode.UNKNOWN_ERROR;
        send({
            type: "permission_reply_response",
            requestId,
            error: createError(code, `Failed to forward permission reply: ${message}`),
        });
    }
}
//# sourceMappingURL=permission-reply.js.map