import{signMlDsa65,verifyMlDsa65}from"./identity.js";import{ok,err}from"./_deps/shared/index.js";export async function createSuccession(e,r,t,n,i,o=6048e5){const a=Date.now(),s=a,c=a+2592e6,u=`${e}||${t}||${i}||${s}||${c}||${o}||${a}`,f=(new TextEncoder).encode(u),_=await signMlDsa65(r,f);if(!_.ok)return err("SIGN_FAILED");const d=await signMlDsa65(n,f);return d.ok?ok({oldDid:e,newDid:t,rotation_sequence:i,effective_at:s,expires_at:c,grace_period_ms:o,timestamp:a,oldSignature:_.value,newSignature:d.value}):err("SIGN_FAILED")}export async function verifySuccession(e,r,t){const n=`${e.oldDid}||${e.newDid}||${e.rotation_sequence}||${e.effective_at}||${e.expires_at}||${e.grace_period_ms}||${e.timestamp}`,i=(new TextEncoder).encode(n),o=await verifyMlDsa65(r,e.oldSignature,i);if(!o.ok)return err("VERIFY_FAILED");const a=await verifyMlDsa65(t,e.newSignature,i);if(!a.ok)return err("VERIFY_FAILED");const s=o.value&&a.value;return ok(s)}export function encodeSuccession(e){return[e.oldDid,e.newDid,e.rotation_sequence.toString(),e.effective_at.toString(),e.expires_at.toString(),e.grace_period_ms.toString(),e.timestamp.toString(),Buffer.from(e.oldSignature).toString("base64"),Buffer.from(e.newSignature).toString("base64")].join("||")}export function decodeSuccession(e){const r=e.split("||");if(9!==r.length)return err("INVALID_FORMAT");const t=r[0],n=r[1],i=r[2],o=r[3],a=r[4],s=r[5],c=r[6],u=r[7],f=r[8];if(!(t&&n&&i&&o&&a&&s&&c&&u&&f))return err("INVALID_FORMAT");const _=parseInt(i,10),d=parseInt(o,10),g=parseInt(a,10),p=parseInt(s,10),S=parseInt(c,10);if(isNaN(_)||_<0||isNaN(d)||d<0||isNaN(g)||g<0||isNaN(p)||p<0||isNaN(S)||S<0)return err("INVALID_TIMESTAMP");try{return ok({oldDid:t,newDid:n,rotation_sequence:_,effective_at:d,expires_at:g,grace_period_ms:p,timestamp:S,oldSignature:new Uint8Array(Buffer.from(u,"base64")),newSignature:new Uint8Array(Buffer.from(f,"base64"))})}catch{return err("INVALID_FORMAT")}}export function verifySuccessionChain(e){if(0===e.length)return ok(!0);if(1===e.length)return ok(!0);for(let r=1;r<e.length;r++){const t=e[r-1];if(e[r].rotation_sequence<=t.rotation_sequence)return err("SUCCESSION_NOT_MONOTONIC")}return ok(!0)}