const e=require("./registration"),{isMemberActive:t,getMemberForDeviceKey:a}=require("./query"),i=require("b4a"),{KeetContractError:r}=require("./errors"),{chatLabelStats:s}=require("./stats"),{trackActivity:l}=require("./hooks"),{contract:{hyperschema:{getEnum:o}}}=require("../../../schema/spec"),d=o("@keet/label-type");async function c({header:e,oplog:l,label:o},{db:c,writer:n}){const[h,E,w,_]=await Promise.all([a(c,n.key),a(c,l.key),c.get("@keet/chat-by-message-id",{oplog:l}),c.get("@keet/threads",{id:0})]);if(!t(h))throw r.INACTIVE_MEMBER();if(!w)throw r.TARGET_MSG_INVALID();if(w.status.isDeleted)throw r.TARGET_MSG_IS_DELETED();if(h.status.isMuted)throw r.MUTED_MEMBER();if(i.equals(h.key,E.key))throw r.TARGET_MSG_IS_OWN();if(await c.get("@keet/chat-labels",{id:w.id,sender:h.key,label:o}))throw r.CHAT_LABEL_EXISTS();if(o===d.Flag&&await async function(){const e=await c.get("@keet/chat-label-digests",{id:w.id});if(!e)return!1;const t=e.labels.find(({label:e})=>e===d.Flag);return!!t&&t.count>=20}())throw r.CHAT_FLAG_LIMIT_EXCEEDED();const u={id:w.id,sender:h.key,clock:_.stats.chat.clock,label:o};return await c.insert("@keet/chat-labels",u),await s(c,_,u,null,e.timestamp),{writer:n,writerMember:h}}async function n({header:e,oplog:i,label:l},{db:o,writer:d}){const[c,n,h]=await Promise.all([a(o,d.key),o.get("@keet/chat-by-message-id",{oplog:i}),o.get("@keet/threads",{id:0})]);if(!t(c))throw r.INACTIVE_MEMBER();if(!n)throw r.TARGET_MSG_INVALID();if(n.status.isDeleted)throw r.TARGET_MSG_IS_DELETED();if(c.status.isMuted)throw r.MUTED_MEMBER();const E=await o.get("@keet/chat-labels",{id:n.id,sender:c.key,label:l});if(!E)throw r.CHAT_LABEL_NOT_FOUND();return await o.delete("@keet/chat-labels",E),await s(o,h,null,E,e.timestamp),{writer:d,writerMember:c}}async function h({header:e,oplog:i},{db:l,writer:o}){const[c,n,h]=await Promise.all([a(l,o.key),l.get("@keet/chat-by-message-id",{oplog:i}),l.get("@keet/threads",{id:0})]);if(!t(c))throw r.INACTIVE_MEMBER();if(!n)throw r.TARGET_MSG_INVALID();if(n.status.isDeleted)throw r.TARGET_MSG_IS_DELETED();if(!c.status.isModerator)throw r.MODERATORS_ONLY();const E=l.find("@keet/chat-labels",{gte:{id:n.id,label:d.Flag},lte:{id:n.id,label:d.Flag}});for await(const t of E)await l.delete("@keet/chat-labels",t),await s(l,h,null,t,e.timestamp)}module.exports={[e]:function(e){e.add("@keet/add-chat-label",l(c)),e.add("@keet/remove-chat-label",l(n)),e.add("@keet/dismiss-chat-reports",h)},CHAT_FLAG_LIMIT:20};