"use client";
import { useCallback, useState } from "react";
import { create } from "@bufbuild/protobuf";
import { RedeemInvitationInputSchema } from "@stigmer/protos/ai/stigmer/iam/invitation/v1/io_pb";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
/**
 * Behavior hook that wraps `invitation.redeem()` with loading and
 * error state.
 *
 * Redeems an invitation by its shareable token. The server validates
 * that the invitation is active, not expired, and not at its
 * redemption limit, then creates an IAM policy granting the
 * configured role to the authenticated user.
 *
 * The redeemer's identity is resolved from the authentication header
 * — the token itself is the authorization mechanism (no FGA check
 * on the invitation resource).
 *
 * Returns the updated {@link Invitation} including the incremented
 * `status.redemptionCount` and the new entry in
 * `status.redemptions`.
 *
 * @example
 * ```tsx
 * const { redeem, isRedeeming, error } = useRedeemInvitation();
 *
 * const invitation = await redeem("abc123...");
 * // invitation.metadata?.org contains the org the user just joined
 * ```
 */
export function useRedeemInvitation() {
    const stigmer = useStigmer();
    const [isRedeeming, setIsRedeeming] = useState(false);
    const [error, setError] = useState(null);
    const clearError = useCallback(() => setError(null), []);
    const redeem = useCallback(async (token) => {
        setIsRedeeming(true);
        setError(null);
        try {
            return await stigmer.invitation.redeem(create(RedeemInvitationInputSchema, { token }));
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
        finally {
            setIsRedeeming(false);
        }
    }, [stigmer]);
    return { redeem, isRedeeming, error, clearError };
}
//# sourceMappingURL=useRedeemInvitation.js.map