import { authedGet, authedPost, type AppviewContext } from "./appview";
import type { XrpcRequestInit } from "./client";

// org.tangled.temp.site.getDomainClaim — domain is absent when unclaimed.
interface DomainClaimResponse {
	domain?: string;
}

const GET_DOMAIN_CLAIM = "org.tangled.temp.site.getDomainClaim";
const CLAIM_DOMAIN = "org.tangled.temp.site.claimDomain";
const RELEASE_DOMAIN = "org.tangled.temp.site.releaseDomain";

// returns the user's active sites domain, or null when none is claimed.
export const getDomainClaim = async (
	ctx: AppviewContext,
	init?: XrpcRequestInit
): Promise<string | null> => {
	const res = await authedGet<DomainClaimResponse>(ctx, GET_DOMAIN_CLAIM, undefined, init);
	return res.domain ?? null;
};

// claims <subdomain>.<sites domain>; the server appends the configured suffix.
export const claimDomain = (
	ctx: AppviewContext,
	subdomain: string,
	init?: XrpcRequestInit
): Promise<void> => authedPost(ctx, CLAIM_DOMAIN, { subdomain }, init).then(() => undefined);

export const releaseDomain = (
	ctx: AppviewContext,
	domain: string,
	init?: XrpcRequestInit
): Promise<void> => authedPost(ctx, RELEASE_DOMAIN, { domain }, init).then(() => undefined);
