import { getTimeToBuild } from "../logic";
import { canPayBuildingCost, getBuildingUpgradeCost } from "../utils";
import type { VillageState } from "../village";


export default function upgradeBuilding(V: VillageState, buildingId: number) {
    const building = V.buildings.find(b => b.id === buildingId);
    if (!building) {
        return false;
    }

    if (building.state.upgrade.isUpgrading) {
        return false;
    }

    if (building.level >= building.maxLevel) {
        return false;
    }

    if (!canPayBuildingCost(V, building)) {
        return false;
    }

    const cost = getBuildingUpgradeCost(V, building);

    V.resources.wood -= cost.wood;
    V.resources.stone -= cost.stone;
    V.resources.iron -= cost.iron;
    V.resources.food -= cost.food;

    building.state.upgrade.isUpgrading = true;
    building.state.upgrade.remainingTime = getTimeToBuild(V, building, building.level + 1);

    return true;
}
