// Generic collection repository; fixed SQL, authenticated scope and bounded row counts.
// The caller supplies trusted, server-side collection name. Never accept it from a request.
function collection(db,origin,accountId,name){
 if(!/^[a-z][a-z0-9-]{0,31}$/.test(name))throw Error("Invalid collection");
 const scope=[origin,accountId,name];
 return {
 async list(){let r=await db.prepare("SELECT id,title,amount FROM bry_collection_records WHERE origin=? AND account_id=? AND collection=? ORDER BY created_at,id LIMIT 16").bind(...scope).all();if(!r.success)throw Error("Read failed");return r.results},
 async apply(plan,id,title,amount){
 let r;
 if(plan===1)r=await db.prepare("INSERT INTO bry_collection_records(origin,account_id,collection,id,title,amount) SELECT ?,?,?,?,?,? WHERE (SELECT COUNT(*) FROM bry_collection_records WHERE origin=? AND account_id=? AND collection=?)<16").bind(...scope,crypto.randomUUID(),title,amount,...scope).run();
 else if(plan===2)r=await db.prepare("UPDATE bry_collection_records SET title=?,amount=? WHERE origin=? AND account_id=? AND collection=? AND id=?").bind(title,amount,...scope,id).run();
 else if(plan===3)r=await db.prepare("DELETE FROM bry_collection_records WHERE origin=? AND account_id=? AND collection=? AND id=?").bind(...scope,id).run();
 else throw Error("Invalid plan");
 if(!r.success)throw Error("Write failed");
 return r.meta.changes?200:plan===1?409:404
 }
 }
}

const collectionSource=routes["/collection.bry"][0],inventorySource=routes["/inventory.bry"][0];
async function inventory(req,db){
 const origin=new URL(req.url).origin,s=await session(req,db,origin),method=req.method;
 if(!["GET","HEAD","POST"].includes(method))return err(req,405,"Method not allowed",{Allow:"GET, HEAD, POST"});
 if(!s)return method==="POST"?err(req,401,"Sign in required"):reply(req,null,303,"text/plain",{Location:"/account"});
 const repo=collection(db,origin,s.id,"inventory"),source=web+"\n"+collectionSource+"\n"+inventorySource;
 if(method==="POST"){
 if(!sameOrigin(req))return err(req,403,"Same-origin form required");
 if(!formType(req))return err(req,415,"Unsupported content type");
 let v;try{v=await form(req,["action","id","title","amount"])}catch(e){return err(req,e.message==="too large"?413:400,"Invalid form")}
 let action=v.get("action")||"",id=v.get("id")||"",title=(v.get("title")||"").trim(),raw=v.get("amount")||"0";
 if(!clean(title)||title.length>64||action.length>12||(id&&!uuid.test(id))||!/^\d{1,5}$/.test(raw))return err(req,400,"Invalid input");
 const amount=Number(raw),plan=Number(run(source,"::2.+8.++5.9.+4.++2.5.+4.++.+5.+8.++5"+"(#@3.+5.+2("+args(action,id,title,amount)+"))"));
 if(![1,2,3].includes(plan))return err(req,400,"Invalid collection command");
 let result=await repo.apply(plan,id,title,amount);
 if(result!==200)return err(req,result,result===409?"Inventory full":"Item not found");
 return reply(req,null,303,"text/plain",{Location:"/inventory"})
 }
 const records=await repo.list(),expr=records.map(r=>"::2.+8.++5.9.++.5.+3"+"("+args(r.id,r.title,String(r.amount))+")").join(" + ")||'""';
 return reply(req,run(source,"::2.+8.++5.+9.++.+5.3.+1"+"("+expr+","+records.length+")"))
}
