// Task 06 CP award service. Caller must authenticate the session; permissions are checked here. import {manualSealDecision} from './seal-entitlements.mjs'; import {grantSealEntitlement,revokeSealEntitlement,activeSealEntitlements} from './seal-entitlement-store.mjs'; import {accessFor} from './permissions.mjs'; import {randomUUID} from 'node:crypto'; export async function manageManualSeal(db,actor,{targetId,seal,action,reason,entitlementId}){ if(!actor?.id)throw new TypeError('Authenticated actor required'); const rights=await accessFor(db,actor); const decision=manualSealDecision({seal,actorAuthorized:rights.nodes.includes('web.accounts.assign')||rights.nodes.includes('cp.accounts.assign'),targetId,actorId:actor.id,action}); if(!decision)return {ok:false,status:403,message:'Award assignment not permitted'}; const target=await db.prepare("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT IN ('!deleted','!banned')").bind(targetId).first(); if(!target)return {ok:false,status:404,message:'Active recipient not found'}; if(action==='grant'){ if(typeof reason!=='string'||!reason.trim()||reason.length>500)return {ok:false,status:400,message:'Reason required (up to 500 characters)'}; const current=await activeSealEntitlements(db,targetId); if(current.some(item=>item.key===seal&&item.source==='staff'))return {ok:true,created:false,message:'Already awarded'}; const result=await grantSealEntitlement(db,{accountId:targetId,seal,sourceKind:'staff',sourceId:randomUUID(),actorId:actor.id,details:{reason:reason.trim()}}); return {ok:true,created:result.created,entitlementId:result.id}; } if(typeof entitlementId!=='string'||!entitlementId)return {ok:false,status:400,message:'Entitlement ID required'}; const current=await activeSealEntitlements(db,targetId); if(!current.some(item=>item.id===entitlementId&&item.key===seal&&item.source==='staff'))return {ok:false,status:404,message:'Staff award not found'}; const result=await revokeSealEntitlement(db,{entitlementId,actorId:actor.id,reason}); return {ok:true,revoked:result.revoked}; }