import{existsSync as f,readFileSync as u}from"node:fs";import{homedir as l}from"node:os";import{join as h}from"node:path";var o=new Map;function w(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let t=h(l(),".zibby","config.json");return f(t)&&JSON.parse(u(t,"utf-8")).sessionToken||null}catch{return null}}function k(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app"}async function y(t){let s=Date.now(),r=o.get(t);if(r&&r.expiresAt>s)return r.data;let i=w();if(!i)throw new Error("No session token. Run `zibby login` first.");let c=`${k()}/integrations/token/${t}`,n=await fetch(c,{method:"GET",headers:{Authorization:`Bearer ${i}`}});if(!n.ok){let p=await n.text().catch(()=>"");throw n.status===404?new Error(`${t} is not connected. Connect it at https://studio.zibby.app/integrations`):n.status===401||n.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${t} token (${n.status}): ${p}`)}let e=await n.json();if(!e||typeof e!="object")throw new Error(`Invalid response from ${t} token endpoint: expected object, got ${typeof e}`);if(t==="jira"){if(!e.token||typeof e.token!="string")throw new Error(`Invalid jira token response: token is ${typeof e.token}, expected string`);if(!e.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(t==="github"&&(!e.token||typeof e.token!="string"))throw new Error(`Invalid github token response: token is ${typeof e.token}, expected string`);let a=((e.expiresInSec||3e3)-120)*1e3;return o.set(t,{data:e,expiresAt:s+a}),e}function b(t){t?o.delete(t):o.clear()}export{b as clearTokenCache,y as resolveIntegrationToken};
