import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import { mintServiceAuth, serviceDidForHost } from "#lib/auth/agent.ts";
import type { XRPCProcedures } from "@atcute/lexicons/ambient";
import { serviceUrlFor, toResponseError } from "#lib/api/_request.ts";
import { nsidOf } from "#lib/api/syntax.ts";
import type { Fetch } from "#lib/fetch.ts";
// spelled out rather than read off the lexicon's schema: the generated module sits in a
// `server/` directory (its nsid's path), which sveltekit refuses to ship to the browser
const REDEEM: keyof XRPCProcedures = "org.tangled.temp.server.redeemInviteCode";
export const REDEEM_NSID = nsidOf(REDEEM);
export const redeemInviteCode = async (
agent: OAuthUserAgent,
knot: string,
code: string,
fetch: Fetch = globalThis.fetch
): Promise<void> => {
const token = await mintServiceAuth(agent, {
aud: serviceDidForHost(knot),
lxm: REDEEM_NSID
});
const response = await fetch(new URL(`/xrpc/${REDEEM_NSID}`, `${serviceUrlFor(knot)}/`), {
method: "POST",
headers: {
"content-type": "application/json",
accept: "application/json",
authorization: `Bearer ${token}`
},
body: JSON.stringify({ code })
});
if (!response.ok) throw await toResponseError(response);
};