'use strict'; /* The world ends (two world days after a node reached the last level; payload { reason, siteId }). Stores the final ranking * snapshot, sets status 'ended', gives the escrow of open trade offers back to its POPs, cancels everything still pending in this world (the world is frozen: no arrival, training or * trade changes anything any more; reads keep working) and tells every operator. Idempotent: an ended world is left alone. */ const { loadWorld } = require('../state'); const E = require('../endgame'); const T = require('../trade'); const { finalRanking } = require('../finalRanking'); module.exports = function worldEnd(ctx, ev) { const { db } = ctx; const world = loadWorld(db, ev.worldId); if (!world || world.status === 'ended') return; const snapshot = finalRanking(db, world, ev.dueAt); db.run('INSERT OR REPLACE INTO world_rankings (world_id, created_at, data) VALUES (?, ?, ?)', world.id, ev.dueAt, JSON.stringify(snapshot)); db.run("UPDATE worlds SET status = 'ended', end_at = ? WHERE id = ?", ev.dueAt, world.id); for (const o of db.all("SELECT * FROM trade_offers WHERE world_id = ? AND status = 'open'", world.id)) T.closeOffer(ctx, o, 'expired', ev.dueAt); // escrow back in its POP: every unit stays accounted for db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE world_id = ? AND status = 'pending' AND id != ?", ev.dueAt, world.id, ev.id); E.notifyWorld(ctx, world.id, 'world_ended', { winner: snapshot.winner, endedAt: ev.dueAt }); };