'use strict'; /* POST /towns/:id/research. One research at a time per POP (a `researchDone` event). +5% attack or defence per level * of one unit type; level n needs a Research lab of level n + RESEARCH.labOffset. Incumbent sites speed it up. */ const R = require('../../public/js/rules.js'); const { GameError } = require('../errors'); const { settle, spend } = require('../state'); const { ownedTown } = require('./build'); const U = require('../military/units'); module.exports = function research(ctx, { userId, townId, unit, stat }) { const { db, now, scheduler } = ctx; const town = ownedTown(db, userId, townId); if (!R.unitDef(unit)) throw new GameError('unknown_unit', { unit }); settle(db, town, now); const busy = !!db.get("SELECT 1 AS x FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' LIMIT 1", town.id); const current = U.researchLevels(db, town.id)[R.researchKey(unit, stat)] || 0; const plan = R.researchPlan(town, unit, stat, current, busy, now, U.researchBonusOf(db, town.ownerId)); if (!plan.ok) throw new GameError(plan.code, { unit, stat, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing }); spend(db, town, plan.cost); const dueAt = now + plan.durationMs; const eventId = scheduler.enqueue({ worldId: town.worldId, townId: town.id, type: 'researchDone', dueAt, payload: { unit, stat, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId }, }); return { eventId, unit, stat, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost }; };