import { getLocation } from "../../../api/locations.js";
import { registerShopTradePolicy } from "../../../api/shops.js";
import { SettlementMarketplaceModel } from "../models/SettlementMarketplaceModel.js";
import { TradeBasinEconomyService } from "./TradeBasinEconomyService.js";
import { TradeGoodsProviderRegistry } from "./TradeGoodsProviderRegistry.js";

export const REGIONAL_MARKETPLACE_TRADE_POLICY_ID = "augur-nexus:regional-marketplace";

export class RegionalMarketplaceTradePolicy {
    static register() {
        registerShopTradePolicy({
            id: REGIONAL_MARKETPLACE_TRADE_POLICY_ID,
            quoteCustomerPurchase: context => this.#quotePurchase(context),
            quoteCustomerSale: context => this.#quoteSale(context)
        });
    }

    static #quotePurchase({ shop, product }) {
        const location = getLocation(shop?.hierarchy?.parentLocationId);
        const rules = SettlementMarketplaceModel.getRules(shop, location);
        const market = TradeBasinEconomyService.getMarketState(location, product?.id);
        if (market.isLocal) return { multiplier: rules.regionalMultiplier, reason: "Produced here and sold at its source price." };
        if (market.isRegionallySupplied) return { multiplier: 1, reason: `Available through ${market.basin.marketName}.` };
        return { multiplier: Math.max(1, rules.importMultiplier), reason: "Imported from beyond this trade network." };
    }

    static #quoteSale({ shop, productReference }) {
        const isTradeGood = TradeGoodsProviderRegistry.get(productReference?.providerId)
            || productReference?.providerId === "augur-nexus:custom-trade-goods";
        if (!isTradeGood || !productReference?.productId) {
            return { allowed: false, disposition: "consume", reason: "This market buys trade goods only." };
        }
        const location = getLocation(shop?.hierarchy?.parentLocationId);
        const rules = SettlementMarketplaceModel.getRules(shop, location);
        if (!rules.buysTradeGoods) return { allowed: false, disposition: "consume", reason: "This market does not buy cargo from travelers." };
        const market = TradeBasinEconomyService.getMarketState(location, productReference.productId);
        if (market.isRegionallySupplied) {
            return { multiplier: rules.regionalMultiplier, disposition: "consume", reason: market.isLocal ? "This good is produced here." : "This trade network already supplies this good." };
        }
        return { multiplier: rules.importMultiplier, disposition: "consume", reason: "No producer in this trade network supplies this good." };
    }
}
