import {randomUUID} from 'node:crypto'; import {PUBLIC_OFFICES} from './public-government.mjs'; const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); // Internal deed primitive. The caller must verify its signed source/key in this // transaction. Election and auction source records are never rewritten here. export async function transferOfficeDeed(tx,{termId,sourceTermId,officeKey,winnerId,playerUuid,sourceId,method,now}){ const office=PUBLIC_OFFICES.find(o=>o.key===officeKey); if(!office||![termId,sourceTermId,winnerId,playerUuid,sourceId].every(uuid)||!['rebellion','war'].includes(method)||!Number.isSafeInteger(now))throw TypeError('Invalid office deed transfer'); const scope=office.kind+':'+office.faction;await tx.query('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',[scope]);await tx.first('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',[scope]); const prior=await tx.first('SELECT * FROM political_office_terms WHERE round_id=?',[sourceId]); if(prior){if(prior.id!==termId||prior.user_id!==winnerId||prior.kind!==office.kind||prior.faction!==office.faction)throw Error('Office transfer reference conflict');return {termId:prior.id,replayed:true};} const active=await tx.query("SELECT * FROM political_office_terms WHERE kind=? AND faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[office.kind,office.faction,office.office,now,now]); if(active.length!==1||active[0].id!==sourceTermId||active[0].user_id===winnerId)throw Error('The incumbent office deed changed'); const source=active[0],person=await tx.first("SELECT a.id FROM site_accounts a JOIN site_game_links g ON g.user_id=a.id WHERE a.id=? AND LOWER(g.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','system_account','memorial')",[winnerId,playerUuid.toLowerCase()]);if(!person)throw Error('Current personal winner identity required'); await tx.query("UPDATE political_office_terms SET outcome='superseded',expires_at=? WHERE id=?",[now,sourceTermId]); await tx.query("INSERT INTO political_office_terms(id,kind,faction,election_start,round_id,application_id,user_id,player_uuid,office,starts_at,expires_at,outcome,streak) VALUES(?,?,?,?,?,NULL,?,?,?,?,?,'winner',0)",[termId,office.kind,office.faction,source.election_start,sourceId,winnerId,playerUuid.toLowerCase(),office.office,now,source.expires_at]); for(const [id,event,payload]of [[sourceTermId,'superseded_by_'+method,{successorTermId:termId,sourceId}],[termId,method+'_awarded',{previousTermId:sourceTermId,previousHolderId:source.user_id,sourceId,method}]])await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,event,JSON.stringify(payload),now]); return {termId,previousTermId:sourceTermId,expiresAt:Number(source.expires_at),replayed:false}; }