import { createBuilding, getBuildingSource } from "../create";
import type { Hex } from "../hexgrid";
import { getTimeToBuild } from "../logic";
import { DEFAULT_TILE, type VillageState } from "../village";


export default function build(V: VillageState, buildingType: string, tile: Hex) {
    const building = getBuildingSource(buildingType);
    const cost = building.cost(1);

    if (
        cost.wood > V.resources.wood
        || cost.stone > V.resources.stone
        || cost.iron > V.resources.iron
        || cost.food > V.resources.food
    ) {
        return false;
    }

    if (V.villageTiles[tile.y][tile.x] !== DEFAULT_TILE) {
        return false;
    }

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

    const newBuilding = createBuilding(buildingType);
    newBuilding.tile = tile;
    newBuilding.level = 0;
    newBuilding.state.upgrade.isUpgrading = true;
    newBuilding.state.upgrade.remainingTime = getTimeToBuild(V, building, 1);

    V.buildings.push(newBuilding);
    V.villageTiles[tile.y][tile.x] = newBuilding.id;

    return true;
}
