import { env } from '$env/dynamic/private';
import {
	Client,
	getBlobCidString,
	isBlobRef,
	type AtIdentifierString,
	type BlobRef
} from '@atproto/lex';

export type RepoInfo = { did: string; pds: string };

/**
 * Reads the configured ATProto repo (DID + PDS) from the environment.
 * Returns null — and logs a warning — when either is missing, so callers can
 * gracefully hide the relevant section instead of throwing.
 */
export function getRepoInfo(warnLabel?: string): RepoInfo | null {
	const did = env.ATPROTO_DID;
	const pds = env.ATPROTO_PDS;
	if (!did || !pds) {
		console.warn(
			`ATPROTO_DID / ATPROTO_PDS are not set${warnLabel ? ` — ${warnLabel} will be hidden.` : '.'}`
		);
		return null;
	}
	return { did, pds };
}

export function createClient(pds: string): Client {
	return new Client(pds);
}

/** The repo DID as the branded identifier type the lexicon client expects. */
export function repoId(did: string): AtIdentifierString {
	return did as AtIdentifierString;
}

/** Builds a public getBlob URL for a blob ref stored on a record. */
export function blobUrl(pds: string, did: string, blob: BlobRef | undefined): string | null {
	if (!blob) return null;
	if (!isBlobRef(blob)) return null;
	const cidString = getBlobCidString(blob);
	return `${pds}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(did)}&cid=${cidString}`;
}
