'use strict'; /* POST /alliances/:id/leave. The leader cannot leave while others remain (transfer first); a leader who is alone * dissolves the alliance. Leaving an alliance you are not in is a no-op. */ const { GameError } = require('../errors'); const A = require('../alliances'); module.exports = function allianceLeave(ctx, { userId, allianceId }) { const { db } = ctx; const alliance = A.getAlliance(db, allianceId); if (!alliance) throw new GameError('not_found', { what: 'alliance' }); const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, alliance.world_id); if (!op) throw new GameError('not_found', { what: 'alliance' }); const m = A.membership(db, op.id); if (!m || m.alliance_id !== alliance.id) return { changed: false }; if (m.role === 'leader') { if (A.memberCount(db, alliance.id) > 1) throw new GameError('leader_must_transfer'); A.dissolve(ctx, alliance.id, 'last_member_left'); return { changed: true, disbanded: true }; } A.removeMember(db, op.id); A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId: op.id, name: op.name, kicked: false }); return { changed: true, disbanded: false }; };