import { createVersion } from "../services/editService";
import { getItemDescriptor } from "../utils";
import { cleanId } from "../utils/id-helper";
export function getCreateAndSwitchToNewVersionCommand({ language, }) {
    return {
        id: "createAndSwitchToNewVersion",
        execute: (context) => execute(context, language),
        label: "Add Version",
        icon: "Plus",
        disabled: (context) => !context.editContext.item?.canLock,
    };
}
async function execute(context, language) {
    if (!context.editContext.item)
        return;
    const descriptor = getItemDescriptor(context.editContext.item);
    if (language)
        descriptor.language = language;
    // Check for field locks from other users.
    // Use global active sessions as a backstop to avoid any stale context snapshots.
    const sessions = (() => {
        try {
            const globalSessions = globalThis.__alpacaActiveSessions;
            if (Array.isArray(globalSessions))
                return globalSessions;
        }
        catch {
            // ignore
        }
        return context.editContext.activeSessions;
    })();
    const itemIdKey = cleanId(descriptor.id) || "";
    const lockedByOthers = sessions.filter((s) => {
        if (!s?.fieldLock)
            return false;
        if (s.sessionId === context.editContext.sessionId)
            return false;
        // Prefer matching by the locked field's item, but fall back to matching the session's
        // current page/item (some fields may belong to a datasource item while still affecting
        // the page item we're versioning).
        const lockItemKey = cleanId(s.fieldLock?.item?.id) || "";
        const sessionItemKey = cleanId(s.item?.id) || "";
        const sessionPageKey = cleanId(s.page?.id) || "";
        return (lockItemKey === itemIdKey ||
            sessionItemKey === itemIdKey ||
            sessionPageKey === itemIdKey);
    });
    if (lockedByOthers.length > 0) {
        const userNames = lockedByOthers.map((s) => s.user.name).join(", ");
        const confirmed = await new Promise((resolve) => {
            context.editContext.confirm({
                header: "Field Locks Detected",
                message: `The following users have active field locks: ${userNames}. Creating a new version may cause their unsaved changes to be lost.`,
                acceptLabel: "Create Version Anyway",
                rejectLabel: "Cancel",
                accept: () => resolve(true),
                reject: () => resolve(false),
            });
        });
        if (!confirmed)
            return;
    }
    await createVersion(descriptor, context.editContext.sessionId);
    await context.editContext.loadItem({
        ...descriptor,
        version: 0,
    }, {
        forceRefresh: true,
    });
}
//# sourceMappingURL=createVersionCommand.js.map