import { Client, simpleFetchHandler } from '@atcute/client';

export { ClientResponseError, isXRPCErrorPayload, ok } from '@atcute/client';
export type { XRPCErrorPayload } from '@atcute/client';

// generated lexicons register ambient types; don't import the barrel at runtime.

export interface BobbinContext {
	readonly xrpc: Client;
	readonly serviceUrl: string;
	readonly fetch: typeof globalThis.fetch;
}

export interface CreateBobbinOptions {
	serviceUrl: string;
	fetch?: typeof globalThis.fetch;
}

export const createBobbinClient = ({ serviceUrl, fetch }: CreateBobbinOptions): BobbinContext => {
	const origin = serviceUrl.replace(/\/+$/, '');
	const boundFetch = fetch ?? globalThis.fetch;
	const xrpc = new Client({ handler: simpleFetchHandler({ service: origin, fetch: boundFetch }) });
	return { xrpc, serviceUrl: origin, fetch: boundFetch };
};

export type QueryValue = string | number | boolean | readonly (string | number)[] | undefined;

export interface XrpcRequestInit {
	signal?: AbortSignal;
	headers?: HeadersInit;
}
