import { ConnectionChangeNotifier } from "./services/ConnectionChangeNotifier.js";
import { ConnectionDatabaseService } from "./services/ConnectionDatabaseService.js";
import { ConnectionStore } from "./services/ConnectionStore.js";
import { registerCoreOpinionInfluenceProviders } from "./services/CoreOpinionInfluenceProviders.js";

const MODULE_ID = "augur-nexus";

export function registerConnectionsFeature() {
    registerCoreOpinionInfluenceProviders();
    const refreshFromPersistence = reason => {
        ConnectionDatabaseService.invalidate();
        ConnectionStore.invalidateCache();
        ConnectionChangeNotifier.notify(ConnectionDatabaseService.getGraph(), { reason });
    };

    Hooks.on("augurNexusConnectionDatabasePointerChanged", () => {
        refreshFromPersistence("databasePointerChanged");
    });

    Hooks.on("augurNexusLegacyConnectionsGraphChanged", () => {
        refreshFromPersistence("legacySettingChanged");
    });

    Hooks.on("updateJournalEntry", (document, _changes, options, userId) => {
        if (!ConnectionDatabaseService.isDatabaseDocument(document)) return;
        ConnectionStore.invalidateCache();
        if (userId === game.user?.id && options?.[MODULE_ID]?.connectionDatabase) return;
        ConnectionChangeNotifier.notify(ConnectionDatabaseService.getChangeMetadata(document), {
            reason: options?.[MODULE_ID]?.reason || "databaseUpdated"
        });
    });

    Hooks.on("preDeleteJournalEntry", (document, options, userId) => {
        if (!ConnectionDatabaseService.isDatabaseDocument(document)) return;
        if (ConnectionDatabaseService.isDeletionAllowed(options)) return;
        if (userId === game.user?.id) {
            ui.notifications?.error?.("The Augur Connections Database is protected and cannot be deleted directly.");
        }
        return false;
    });

    Hooks.on("deleteJournalEntry", document => {
        if (!ConnectionDatabaseService.isDatabaseDocument(document)) return;
        refreshFromPersistence("databaseDeleted");
    });

    Hooks.once("ready", async () => {
        const document = await ConnectionDatabaseService.initialize();
        ConnectionStore.invalidateCache();
        const graph = ConnectionDatabaseService.getGraph();
        ConnectionChangeNotifier.notify(graph, { reason: "databaseReady" });
        Hooks.callAll("augurNexusConnectionsReady", { graph, document });
    });
}
