'use strict'; /* * POST /backbone/:id/withdraw {fromTownId, units?}: units of one of YOUR POPs that stand in a landing site go home. Only their owner can * call them back (the holding alliance has no way to send somebody else's units away; leaving the alliance does it automatically). * `units` defaults to the whole group. They stop defending the site and stop drawing the owner's power at once, and drive home as a * return movement (so they are in no battle on the way). Works whoever holds the site now, also after it changed hands. */ const { GameError } = require('../errors'); const { ownedTown } = require('./build'); const ctxOf = require('../military/ctx'); const U = require('../military/units'); const G = require('../military/garrison'); const E = require('../endgame'); module.exports = function withdrawGarrison(ctx0, { userId, siteId, fromTownId, units }) { const ctx = ctxOf(ctx0); const { db } = ctx; const site = E.siteRow(db, siteId); if (!site) throw new GameError('not_found', { what: 'landing site' }); const owner = ownedTown(db, userId, fromTownId); if (owner.worldId !== site.world_id) throw new GameError('not_found', { what: 'town' }); const have = G.ownedAt(db, site.id, owner.id); let take = units && Object.keys(units).length ? U.cleanUnits(units) : have; take = Object.fromEntries(Object.entries(take).filter(([, n]) => n > 0)); if (U.isEmpty(take)) throw new GameError('not_enough_units', { reason: 'nothing stationed' }); for (const k of Object.keys(take)) if ((have[k] || 0) < take[k]) throw new GameError('not_enough_units', { unit: k, have: have[k] || 0, want: take[k] }); const mv = G.sendHome(ctx, site, owner.id, take, { withdrawn: true }); if (!mv) throw new GameError('conflict', { what: 'no POP to return to' }); return { movementId: mv.id, siteId: site.id, fromTownId: owner.id, units: take, arriveAt: mv.arriveAt }; };