import { ConnectionStore } from "./ConnectionStore.js";
import { ConnectionTargetResolver } from "./ConnectionTargetResolver.js";
import { TradingCenterService } from "./TradingCenterService.js";

export class TradeNetworkService {
    static getProjection({ user = game.user, includeHidden = false } = {}) {
        const revealHidden = includeHidden === true && game.user?.isGM === true && user?.isGM === true;
        const graph = ConnectionStore.getGraphContext().graph;
        const nodes = new Map();
        const edges = [];

        for (const edge of Object.values(graph.edges || {})) {
            if (edge?.relationType !== TradingCenterService.RELATION_TYPE) continue;
            const centerNode = graph.nodes?.[edge.sourceNodeId] || null;
            const locationNode = graph.nodes?.[edge.targetNodeId] || null;
            if (!this.#isLocation(centerNode) || !this.#isLocation(locationNode)) continue;
            if (!revealHidden && !ConnectionStore.canUserSeeConnection(edge, user)) continue;
            if (!revealHidden && (!ConnectionTargetResolver.canUserSeeNode(centerNode, user)
                || !ConnectionTargetResolver.canUserSeeNode(locationNode, user))) continue;

            nodes.set(centerNode.id, this.#nodeView(centerNode));
            nodes.set(locationNode.id, this.#nodeView(locationNode));
            edges.push({
                id: edge.id,
                centerNodeId: centerNode.id,
                locationNodeId: locationNode.id,
                playerVisibility: ConnectionStore.getConnectionPlayerVisibility(edge),
                resourceFlows: foundry.utils.deepClone(edge.resourceFlows || [])
            });
        }

        return {
            nodes: [...nodes.values()].sort((left, right) => left.name.localeCompare(right.name)),
            edges: edges.sort((left, right) => left.id.localeCompare(right.id))
        };
    }

    static #nodeView(node) {
        const display = ConnectionTargetResolver.resolveDisplayNodeSync(node) || node;
        return {
            nodeId: node.id,
            entityId: String(node.entityId || ""),
            name: String(display.name || "Unknown Location"),
            imageSrc: String(display.img || ""),
            subtitle: String(display.subtitle || "Location")
        };
    }

    static #isLocation(node) {
        return node?.kind === "nexus-entity" && node.entityType === "location";
    }
}
