import {identity} from './auth.mjs'; import {readGovernmentOffices} from './public-government.mjs'; const assets='https://www.dunerealms.com/assets/'; // Public projections contain no account identifiers, private keys or financial records. export async function readPublicOrganisations(db,kind,now=Date.now()){ if(kind==='politics')return (await readGovernmentOffices(db,now)).map(o=>({id:o.key,tag:o.key,name:o.scope,description:o.description,emblem:o.art?.startsWith('https://')?o.art:assets+'seals/'+o.art,owner_username:o.holder?.username,owner_name:o.holder?.name,member_count:o.holder?1:0,institution_key:o.key,standing:o.state,realm:o.chamber,created_at:null,term:o.term,members:o.holder?[{username:o.holder.username,title:o.name}]:[]})); if(kind!=='company')throw TypeError('Unknown organisation register'); const {results=[]}=await db.prepare("SELECT c.slug,c.name,c.description,c.created_at,a.username AS owner_username,a.display_name AS owner_name FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id AND a.password_hash NOT LIKE '!%' WHERE c.status='active' ORDER BY c.name").all(); return results.map(c=>({...c,id:c.slug,tag:c.slug,emblem:assets+'guild.webp',standing:'Registered company',realm:'Spacing Guild ยท Commerce',member_count:null,members:c.owner_username?[{username:c.owner_username,title:'Chief Executive'}]:[]})); } export function createPublicOrganisations(db,{clock=Date.now,authenticate=r=>identity(r,db)}={}){return async request=>{ const url=new URL(request.url),match=/^\/api\/public\/(companies|political-houses)(?:\/([a-z0-9_-]{1,64}))?\/?$/i.exec(url.pathname); const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}}); if(!['GET','HEAD'].includes(request.method))return reply({message:'Read-only organisation register.'},405); if(!match||url.search)return reply({message:'Organisation not found.'},404); // Registers are community-visible to signed-in users; individual profiles stay public. if(!match[2]&&!await authenticate(request))return reply({message:'Sign in to browse the organisation register.'},401); try{const kind=match[1]==='companies'?'company':'politics',rows=await readPublicOrganisations(db,kind,clock()),record=match[2]?rows.find(r=>r.tag.toLowerCase()===match[2].toLowerCase()):null; if(match[2]&&!record)return reply({message:'Organisation not found.'},404); return request.method==='HEAD'?new Response(null,{headers:{'Cache-Control':'no-store'}}):reply(record?{kind,organisation:record}:{kind,organisations:rows}); }catch{return reply({message:'The organisation register is temporarily unavailable.'},503);} };}