import { ShopModel } from "./models/ShopModel.js";
import { registerBundledShopIntegrations } from "./integrations/registerBundledShopIntegrations.js";
import { ShopCanvasBridge } from "./services/ShopCanvasBridge.js";
import { ShopTransactionService } from "./services/ShopTransactionService.js";
import { ShopStore } from "./services/ShopStore.js";
import { ShopDerivedNameService } from "./services/ShopDerivedNameService.js";
import { ConnectionStore } from "../connections/services/ConnectionStore.js";
import { ConnectionTargetResolver } from "../connections/services/ConnectionTargetResolver.js";

function isResponsibleGM() {
    if (!game.user?.isGM) return false;
    const activeGM = game.users?.activeGM || game.users?.find(user => user.active && user.isGM);
    return !activeGM || activeGM.id === game.user.id;
}

function removeDeletedShopConnections(document) {
    if (!isResponsibleGM()) return;
    const target = ConnectionTargetResolver.fromDocument(document, { category: "service" });
    if (!target) return;
    void ConnectionStore.removeConnectionsForTarget(target).catch(error => {
        console.error("Augur Nexus | Failed to remove connections for a deleted Shop.", error);
    });
}

export function registerShopsFeature() {
    registerBundledShopIntegrations();
    ShopCanvasBridge.registerHooks();
    ShopDerivedNameService.registerHooks();
    Hooks.on("createJournalEntry", document => {
        if (!ShopModel.isShopDocument(document)) return;
        const shop = ShopStore.upsertDocument(document);
        Hooks.callAll("augurNexusShopsChanged", { reason: "documentCreate", shop, document });
    });
    Hooks.on("updateJournalEntry", document => {
        const previous = ShopStore.getShop(document?.id);
        if (ShopModel.isShopDocument(document)) {
            const shop = ShopStore.upsertDocument(document);
            Hooks.callAll("augurNexusShopsChanged", { reason: "documentUpdate", shop, document });
        } else if (previous) {
            ShopStore.removeDocument(document);
            Hooks.callAll("augurNexusShopsChanged", { reason: "documentUpdateRemoved", shop: previous, document: null });
        }
    });
    Hooks.on("deleteJournalEntry", (document, options = {}) => {
        const shop = ShopStore.getShop(document?.id) || ShopModel.fromDocument(document);
        if (!shop) return;
        const managedCascade = options?.["augur-nexus"]?.managedCascade === true;
        if (!managedCascade) removeDeletedShopConnections(document);
        ShopStore.removeDocument(document);
        if (managedCascade) return;
        Hooks.callAll("augurNexusShopsChanged", { reason: "documentDelete", shop, document: null });
    });
    Hooks.once("ready", () => {
        ShopStore.rebuildIndex();
        ShopTransactionService.registerSocket();
    });
}
