"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useListModerators = useListModerators;
exports.useAddModerator = useAddModerator;
exports.useRemoveModerator = useRemoveModerator;
const react_1 = require("react");
const xrpc_1 = require("./xrpc");
/**
 * Hook to list all moderators for the current user's stream.
 * Fetches place.stream.moderation.permission records from the user's repo.
 */
function useListModerators() {
    const agent = (0, xrpc_1.usePDSAgent)();
    const [moderators, setModerators] = (0, react_1.useState)([]);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [error, setError] = (0, react_1.useState)(null);
    const [refreshTrigger, setRefreshTrigger] = (0, react_1.useState)(0);
    const refresh = (0, react_1.useCallback)(() => {
        setRefreshTrigger((prev) => prev + 1);
    }, []);
    (0, react_1.useEffect)(() => {
        if (!agent?.did) {
            setModerators([]);
            setError(null);
            return;
        }
        const fetchModerators = async () => {
            setIsLoading(true);
            setError(null);
            try {
                const result = await agent.place.stream.moderation.permission.list({
                    repo: agent.did,
                });
                const records = result.records.map((record) => {
                    const rkey = record.uri.split("/").pop();
                    return {
                        uri: record.uri,
                        cid: record.cid || "",
                        value: record.value,
                        rkey: rkey || "",
                    };
                });
                setModerators(records);
            }
            catch (err) {
                setError(`Failed to fetch moderators: ${err instanceof Error ? err.message : "Unknown error"}`);
                setModerators([]);
            }
            finally {
                setIsLoading(false);
            }
        };
        fetchModerators();
    }, [agent?.did, refreshTrigger]);
    return {
        moderators,
        isLoading,
        error,
        refresh,
    };
}
/**
 * Hook to add a new moderator.
 * Creates a place.stream.moderation.permission record in the current user's repo.
 */
function useAddModerator() {
    const agent = (0, xrpc_1.usePDSAgent)();
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const addModerator = async (params) => {
        if (!agent?.did) {
            throw new Error("Not logged in");
        }
        if (params.permissions.length === 0) {
            throw new Error("At least one permission must be selected");
        }
        setIsLoading(true);
        try {
            // Resolve handle to DID if needed
            let moderatorDID = params.moderatorDID.trim();
            if (!moderatorDID.startsWith("did:")) {
                if (moderatorDID.startsWith("@")) {
                    moderatorDID = moderatorDID.substring(1); // Remove @
                }
                try {
                    const resolved = await agent.com.atproto.identity.resolveHandle({
                        handle: moderatorDID,
                    });
                    moderatorDID = resolved.data.did;
                }
                catch (e) {
                    throw new Error(`Invalid DID or handle: ${moderatorDID}. Please use a valid DID (did:plc:...) or handle (@handle.bsky.social)`);
                }
            }
            const record = {
                $type: "place.stream.moderation.permission",
                moderator: moderatorDID,
                permissions: params.permissions,
                createdAt: new Date().toISOString(),
            };
            if (params.expirationTime) {
                record.expirationTime = params.expirationTime;
            }
            const result = await agent.place.stream.moderation.permission.create({ repo: agent.did }, record);
            return result;
        }
        finally {
            setIsLoading(false);
        }
    };
    return { addModerator, isLoading };
}
/**
 * Hook to remove a moderator.
 * Deletes a place.stream.moderation.permission record by its rkey.
 */
function useRemoveModerator() {
    const agent = (0, xrpc_1.usePDSAgent)();
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const removeModerator = async (rkey) => {
        if (!agent?.did) {
            throw new Error("Not logged in");
        }
        setIsLoading(true);
        try {
            await agent.place.stream.moderation.permission.delete({
                repo: agent.did,
                rkey,
            });
        }
        finally {
            setIsLoading(false);
        }
    };
    return { removeModerator, isLoading };
}
//# sourceMappingURL=moderator-management.js.map