'use strict'; /* POST /towns/:id/build. Validate ownership and rules (rules.buildPlan), pay, enqueue the completion event. */ const R = require('../../public/js/rules.js'); const { GameError } = require('../errors'); const { loadTown, settle, spend, pendingBuilds } = require('../state'); module.exports = function build(ctx, { userId, townId, key }) { const { db, now, scheduler } = ctx; const town = ownedTown(db, userId, townId); settle(db, town, now); const pending = pendingBuilds(db, town.id); const plan = R.buildPlan(town, key, now, pending); if (!plan.ok) { throw new GameError(plan.code, { key, type: plan.type, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing }); } spend(db, town, plan.cost); const id = scheduler.enqueue({ worldId: town.worldId, townId: town.id, type: 'buildDone', dueAt: now + plan.durationMs, payload: { key, type: plan.type, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId }, }); return { eventId: id, key, type: plan.type, toLevel: plan.toLevel, startedAt: now, dueAt: now + plan.durationMs, cost: plan.cost }; }; // The town, if the user owns it; otherwise not_found (never reveal that a foreign town exists). function ownedTown(db, userId, townId) { const row = db.get(`SELECT t.id FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ? AND o.user_id = ?`, townId, userId); const town = row ? loadTown(db, row.id) : null; if (!town) throw new GameError('not_found', { what: 'town' }); return town; } module.exports.ownedTown = ownedTown;