import { NexusLineageManager } from "../../nexus/services/NexusLineageManager.js";
import { LocationEntityStore } from "../../campaign-entities/services/LocationEntityStore.js";
import { CampaignEntityVisibilityManager } from "../../campaign-entities/services/CampaignEntityVisibilityManager.js";

function siteKey(row = {}) {
    return row.parentSceneId && row.siteId
        ? `site:${row.parentSceneId}:${row.siteId}`
        : null;
}

function buildNodes({ lineageRows = null, includeHidden = false } = {}) {
    const rows = Array.isArray(lineageRows)
        ? lineageRows
        : NexusLineageManager.getLineageRows().rows;
    const ownerBySceneId = new Map(LocationEntityStore.getLocations()
        .filter(location => includeHidden || CampaignEntityVisibilityManager.canUserSee(location, game.user))
        .filter(location => location.scenes?.primarySceneId)
        .map(location => [location.scenes.primarySceneId, `location:${location.id}`]));
    const keyByLineageId = new Map(rows.map(row => [
        row.id,
        siteKey(row) || ownerBySceneId.get(row.sceneId) || `scene:${row.sceneId || row.id}`
    ]));

    return rows.filter(row => siteKey(row) || !ownerBySceneId.has(row.sceneId)).map(row => {
        const key = keyByLineageId.get(row.id);
        const isSite = !!siteKey(row);
        return {
            ...row,
            key,
            type: isSite ? "site" : "scene",
            objectId: isSite ? key : (row.sceneId || row.id),
            parentKey: keyByLineageId.get(row.parentNodeId) || row.parentNodeId || null,
            lineageNode: true,
            lineageId: row.id,
            searchText: [row.name, row.typeLabel].filter(Boolean).join(" ").toLocaleLowerCase(),
            canContainChildren: true
        };
    });
}

export const ScenePlaceProvider = {
    type: "scene",
    pluralLabel: "Scenes",
    allowedParentTypes: [],
    listNodes(options = {}) {
        return buildNodes(options).filter(node => node.type === "scene");
    }
};

export const SitePlaceProvider = {
    type: "site",
    pluralLabel: "Sites",
    allowedParentTypes: [],
    listNodes(options = {}) {
        return buildNodes(options).filter(node => node.type === "site");
    }
};
