import { ConnectionTargetResolver } from "../../connections/services/ConnectionTargetResolver.js";
import { CampaignEntityVisibilityManager } from "../../campaign-entities/services/CampaignEntityVisibilityManager.js";
import { LocationEntityStore } from "../../campaign-entities/services/LocationEntityStore.js";
import { ShopModel } from "../models/ShopModel.js";
import { ShopStore } from "./ShopStore.js";

const getParentLocationId = shop => String(shop?.hierarchy?.parentLocationId || "");

export const ShopPlaceProvider = {
    type: "shop",
    allowedParentTypes: ["location"],
    pluralLabel: "Shops",

    listNodes({ includeHidden = false } = {}) {
        const locations = new Map(LocationEntityStore.getLocations().map(location => [location.id, location]));
        return ShopStore.getShops().filter(shop => {
            const parentId = getParentLocationId(shop);
            if (!parentId || includeHidden) return true;
            const parent = locations.get(parentId);
            return parent ? CampaignEntityVisibilityManager.canUserSee(parent, game.user) : game.user.isGM;
        }).map(shop => {
            const document = ShopStore.resolveDocument(shop.id);
            const parentLocationId = getParentLocationId(shop);
            return {
                key: `shop:${shop.id}`,
                type: "shop",
                objectId: shop.id,
                parentKey: parentLocationId ? `location:${parentLocationId}` : null,
                entityId: shop.id,
                entityType: "shop",
                shopId: shop.id,
                name: shop.name,
                subtitle: parentLocationId ? "Shop" : "Independent Shop",
                searchText: shop.name,
                imageSrc: ShopModel.getImage(shop),
                iconSrc: ShopModel.getImage(shop),
                placementImageSrc: ShopModel.getImage(shop) || "icons/svg/coins.svg",
                accent: ShopModel.getAccent(shop),
                uuid: shop.uuid || "",
                connectionTarget: document ? ConnectionTargetResolver.fromDocument(document, { category: "service" }) : null,
                isLocation: false,
                isShop: true,
                canContainChildren: false,
                isPlayerHidden: false,
                playerVisibilityLabel: "",
                playerVisibilityIcon: ""
            };
        });
    },

    async open(node) {
        const { openShop } = await import("../../../api/shops.js");
        return openShop(node.objectId);
    },

    setParent(node, parent) {
        const location = parent?.type === "location" ? LocationEntityStore.getLocation(parent.objectId) : null;
        return ShopStore.updateShop(node.objectId, {
            hierarchy: { parentLocationId: location?.id || null }
        });
    },

    deleteNode(node) {
        return ShopStore.deleteShop(node.objectId);
    }
};
