import {z} from 'zod';
import {type DB,ApiError,all,one,event,write} from './commons.ts';
export function authorizeModerator(email:string|undefined|null,configured:string|undefined){if(!email||!configured||email.toLowerCase()!==configured.toLowerCase())throw new ApiError(403,'FORBIDDEN','Site owner sign-in required');}
export async function moderationQueue(db:DB){return {tasks:await all(db,"SELECT * FROM tasks WHERE moderation_status!='approved' ORDER BY created_at DESC LIMIT 100"),reviewable:await all(db,"SELECT t.*,r.id AS result_id,r.content AS result_content FROM tasks t JOIN agents a ON a.id=t.creator JOIN results r ON r.task_id=t.id WHERE a.managed=1 AND a.demo=0 AND t.moderation_status='approved' AND t.accepted_result_id IS NULL AND EXISTS(SELECT 1 FROM verifications v JOIN agents reviewer ON reviewer.id=v.author WHERE v.result_id=r.id AND v.verdict='agree' AND reviewer.demo=0) AND NOT EXISTS(SELECT 1 FROM verifications v WHERE v.result_id=r.id AND v.verdict='dispute') LIMIT 100"),privacy_requests:await all(db,'SELECT task_id,privacy_requested_at FROM human_problems WHERE privacy_requested_at IS NOT NULL'),notifications:await all(db,"SELECT result_id,task_id,status,attempted_at FROM notifications WHERE status!='sent' LIMIT 100"),reports:await all(db,'SELECT * FROM reports ORDER BY created_at DESC LIMIT 100')};}
export async function moderate(db:DB,input:unknown){const p=z.object({task_id:z.string().uuid(),decision:z.enum(['approved','quarantined']),reason:z.string().trim().min(10).max(1000)}).strict().parse(input);if(!await one(db,'SELECT id FROM tasks WHERE id=?',p.task_id))throw new ApiError(404,'NOT_FOUND','Task not found');await db.batch([db.prepare('UPDATE tasks SET moderation_status=?,updated_at=? WHERE id=?').bind(p.decision,new Date().toISOString(),p.task_id),event(db,null,'moderated','tasks',p.task_id,p.decision+': '+p.reason)]);return one(db,'SELECT * FROM tasks WHERE id=?',p.task_id);}

export async function acceptReviewed(db:DB,input:unknown){const p=z.object({task_id:z.string().uuid(),result_id:z.string().uuid(),reason:z.string().trim().min(20).max(1000),criteria_checked:z.literal(true)}).strict().parse(input);const t=await one(db,'SELECT * FROM tasks WHERE id=?',p.task_id);if(!t)throw new ApiError(404,'NOT_FOUND','Task not found');const creator=await one(db,'SELECT * FROM agents WHERE id=?',t.creator);if(!creator?.managed||creator.demo)throw new ApiError(403,'FORBIDDEN','Only site-curated and human-submitted problems can be accepted here');if(!await one(db,"SELECT v.id FROM verifications v JOIN agents a ON a.id=v.author WHERE v.result_id=? AND v.verdict='agree' AND a.demo=0",p.result_id))throw new ApiError(409,'UNVERIFIED','A non-demo eligible review is required');const result=await write(db,['tasks',t.id,'complete'],{result_id:p.result_id},creator);await event(db,null,'acceptance explanation','tasks',t.id,p.reason).run();return result;}
export async function removeContact(db:DB,input:unknown){const p=z.object({task_id:z.string().uuid()}).strict().parse(input);await db.prepare('DELETE FROM human_problems WHERE task_id=? AND privacy_requested_at IS NOT NULL').bind(p.task_id).run();return {status:'private_record_removed'};}
