import {
    canSetTradingCenter,
    clearTradingCenter,
    getTradingCenter,
    setTradingCenter
} from "../../../api/trade-connections.js";
import { getLocation, getLocationConnectionTarget } from "../../../api/locations.js";
import { TradeRegionSceneService } from "./TradeRegionSceneService.js";

export class TradeRouteService {
    static async changeTradingCenter({ locationId = "", centerLocationId = "", sceneId = "", confirmReplacement = true } = {}) {
        if (!game.user?.isGM) throw new Error("Only a GM can change regional trade routes.");
        const location = getLocation(locationId);
        const locationTarget = getLocationConnectionTarget(location);
        if (!location || !locationTarget) throw new Error("The Location could not be resolved.");
        const resolvedSceneId = String(sceneId || TradeRegionSceneService.resolveSceneId(location) || "");
        const center = centerLocationId ? getLocation(centerLocationId) : null;
        const centerTarget = center ? getLocationConnectionTarget(center) : null;
        const current = getTradingCenter(locationTarget, { includeHidden: true });
        if (String(centerLocationId || "") === String(current?.center?.entityId || "")) {
            return { changed: false, cancelled: false, sceneId: resolvedSceneId, tradingCenter: current };
        }
        if (centerLocationId && !center) throw new Error("The dropped Location could not be found.");
        if (center) {
            if (!resolvedSceneId || !TradeRegionSceneService.isLocationOnScene(location, resolvedSceneId)
                || !TradeRegionSceneService.isLocationOnScene(center, resolvedSceneId)) {
                throw new Error("A trade destination must be on the same regional Scene as this Location.");
            }
            if (!TradeRegionSceneService.isTradingCenter(center)) {
                throw new Error("Only a settlement can serve as a trade destination.");
            }
            if (!centerTarget || !canSetTradingCenter(locationTarget, centerTarget)) {
                throw new Error("That trade route would be invalid or create a cycle.");
            }
        }
        if (current && confirmReplacement && !(await this.#confirmRouteChange({
            clearing: !centerTarget,
            currentName: current.center?.name,
            nextName: center?.display?.name || centerTarget?.name
        }))) return { changed: false, cancelled: true, sceneId: resolvedSceneId, tradingCenter: current };

        if (centerTarget) await setTradingCenter(locationTarget, centerTarget, { clearPreviousFlows: true });
        else if (current) await clearTradingCenter(locationTarget, { edgeId: current.edgeId, clearResourceFlows: true });
        Hooks.callAll("augurNexusTradeNetworkChanged", { locationId: location.id, sceneId: resolvedSceneId });
        this.reconcileRegionalMarkets({ sceneId: resolvedSceneId, fallbackLocationId: location.id });
        return { changed: true, cancelled: false, sceneId: resolvedSceneId, tradingCenter: getTradingCenter(locationTarget, { includeHidden: true }) };
    }

    static reconcileRegionalMarkets({ sceneId = "", fallbackLocationId = "" } = {}) {
        Hooks.callAll("augurNexusTradeMarketsReconcile", {
            sceneId: String(sceneId || ""),
            locationIds: TradeRegionSceneService.getRegionLocations(sceneId).map(location => location.id),
            fallbackLocationId: String(fallbackLocationId || "")
        });
    }

    static #confirmRouteChange({ clearing = false, currentName = "the current trade destination", nextName = "the new trade destination" } = {}) {
        return foundry.applications.api.DialogV2.confirm({
            window: { title: clearing ? "Clear Trade Route" : "Change Trade Destination" },
            content: `<div class="nexus-delete-confirm"><p>${clearing ? `Clear the relationship with <strong>${foundry.utils.escapeHTML(currentName)}</strong>?` : `Change the trade destination from <strong>${foundry.utils.escapeHTML(currentName)}</strong> to <strong>${foundry.utils.escapeHTML(nextName)}</strong>?`}</p></div>`,
            yes: { label: clearing ? "Clear Route" : "Change Route", icon: "fas fa-route" },
            no: { label: "Cancel", icon: "fas fa-xmark" }
        });
    }
}
