import {type DB,all} from './commons.ts';
export type MailEnv={RESEND_API_KEY?:string;NOTIFICATION_FROM?:string};
export function mailEnabled(env:MailEnv){return Boolean(env.RESEND_API_KEY&&env.NOTIFICATION_FROM);}
// Only a moderator POST dispatches. No mail or user-controlled destinations on public reads.
export async function dispatchNotifications(db:DB,env:MailEnv,send:typeof fetch=fetch){if(!mailEnabled(env))return {status:'not_configured',sent:0};let sent=0;
 const rows=await all(db,`SELECT n.*,h.email FROM notifications n JOIN human_problems h ON h.task_id=n.task_id JOIN tasks t ON t.id=n.task_id WHERE n.status='pending' AND h.privacy_requested_at IS NULL AND t.status='completed' AND t.accepted_result_id=n.result_id AND t.moderation_status='approved' AND NOT EXISTS(SELECT 1 FROM verifications v WHERE v.result_id=n.result_id AND v.verdict='dispute') LIMIT 20`);
 for(const n of rows){const stamp=new Date().toISOString();const lock=await db.prepare("UPDATE notifications SET status='sending',attempted_at=? WHERE result_id=? AND status='pending' RETURNING result_id").bind(stamp,n.result_id).first();if(!lock)continue;
 try{const r=await send('https://api.resend.com/emails',{method:'POST',headers:{Authorization:'Bearer '+env.RESEND_API_KEY,'Content-Type':'application/json','Idempotency-Key':'otr-result-'+n.result_id},body:JSON.stringify({from:env.NOTIFICATION_FROM,to:[n.email],subject:'Your OpenTaskRelay problem has an accepted result',text:'Your public problem has completed its acceptance process. Read the result, evidence and current review status: https://opentaskrelay.com/trophy-case/'+n.task_id+'\n\nAcceptance is not a guarantee of truth. Future reviews or corrections remain visible.',}),signal:AbortSignal.timeout(10000)});if(!r.ok){await db.prepare("UPDATE notifications SET status=? WHERE result_id=?").bind(r.status===429?'pending':'failed',n.result_id).run();continue}const payload=await r.json() as {id?:string};if(!payload.id)throw new Error('Missing delivery receipt');await db.prepare("UPDATE notifications SET status='sent',sent_at=?,provider_id=? WHERE result_id=?").bind(stamp,payload.id,n.result_id).run();sent++;}catch{await db.prepare("UPDATE notifications SET status='uncertain' WHERE result_id=?").bind(n.result_id).run();}}
 return {status:'processed',sent};}
