import{ok,err}from"./_deps/shared/index.js";import{createSignedEnvelope}from"./envelope.js";const DEFAULT_POLL_INTERVAL_MS=2e3,DEFAULT_TTL_MS=3e5,MAX_POLL_ITERATIONS=200;export async function requestAuth(e,t,r){const n=t.ttlMs??3e5,a=t.pollIntervalMs??2e3,o={recipientDid:t.to,action:t.action,metadata:t.metadata??{},ttlMs:n},i=await createSignedEnvelope({senderDid:e.did,recipientDid:t.to,scope:"xlock:challenge",plaintext:(new TextEncoder).encode(JSON.stringify(o)),privateKey:e.identity.privateKey});if(!i.ok)return err("INVALID_REQUEST");let s,c;try{const e=await fetch(`${r.gatewayUrl}/gateway/auth/challenge`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i.value)});if(429===e.status)return err("RATE_LIMITED");if(!e.ok){const t=await e.json().catch(()=>null),r=t?.error?.code;return err(r??"INVALID_REQUEST")}const t=await e.json();s=t.challengeId,c=t.expiresAt}catch{return err("INVALID_REQUEST")}return pollChallengeStatus(s,c,a,r)}export async function respondToChallenge(e,t,r,n){const a={challengeId:t,approved:r,timestamp:Date.now()},o=await createSignedEnvelope({senderDid:e.did,recipientDid:e.did,scope:"xlock:respond",plaintext:(new TextEncoder).encode(JSON.stringify(a)),privateKey:e.identity.privateKey});if(!o.ok)return err("INVALID_REQUEST");try{const e=await fetch(`${n.gatewayUrl}/gateway/auth/respond`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o.value,challengeId:t,approved:r,responseEnvelope:o.value})});if(!e.ok){const t=await e.json().catch(()=>null),r=t?.error?.code;return err(r??"INVALID_REQUEST")}return ok(void 0)}catch{return err("INVALID_REQUEST")}}export function onChallenge(e,t){const r=e=>{try{const r=JSON.parse(e.data);"auth:challenge"===r.type&&r.data&&t(r.data)}catch{}};return e.addEventListener("message",r),()=>e.removeEventListener("message",r)}export function generateRegistrationQR(e){const t=new URLSearchParams({app:e.appName,did:e.appDid,registry:e.registryUrl,callback:e.callbackUrl});return e.appIcon&&t.set("icon",e.appIcon),`xlock://register?${t.toString()}`}async function pollChallengeStatus(e,t,r,n){for(let a=0;a<200;a++){if(Date.now()>t)return err("CHALLENGE_EXPIRED");await sleep(r);try{const t=await fetch(`${n.gatewayUrl}/gateway/auth/status/${e}`,{headers:{Authorization:`Bearer ${n.accessToken}`}});if(!t.ok){if(404===t.status)return err("CHALLENGE_NOT_FOUND");continue}const r=await t.json();if("approved"===r.status)return ok({challengeId:r.challengeId,approved:!0,respondedAt:r.respondedAt,envelope:r.envelope});if("denied"===r.status)return ok({challengeId:r.challengeId,approved:!1,respondedAt:r.respondedAt});if("expired"===r.status)return err("CHALLENGE_EXPIRED")}catch{}}return err("CHALLENGE_TIMEOUT")}function sleep(e){return new Promise(t=>setTimeout(t,e))}