import { env } from '$env/dynamic/private';

const cleanUrl = (value: string | undefined, fallback: string) => {
	const raw = value?.trim() || fallback;
	return raw.replace(/\/+$/, '');
};

export type WebConfig = {
	bobbinUrl: string;
	apiUrl: string;
	knotResolverUrl: string;
	camoUrl: string;
};

export type PublicWebConfig = Pick<
	WebConfig,
	'bobbinUrl' | 'apiUrl' | 'knotResolverUrl' | 'camoUrl'
>;

type WebConfigEnv = {
	BOBBIN_URL?: string;
	TANGLED_API_URL?: string;
	API_URL?: string;
	KNOT_RESOLVER_URL?: string;
	CAMO_URL?: string;
};

export const resolveConfig = (values: WebConfigEnv): WebConfig => ({
	bobbinUrl: cleanUrl(values.BOBBIN_URL, 'http://127.0.0.1:8090'),
	apiUrl: cleanUrl(values.TANGLED_API_URL ?? values.API_URL, 'http://127.0.0.1:8080'),
	knotResolverUrl: cleanUrl(values.KNOT_RESOLVER_URL, 'https://knot1.tangled.sh'),
	camoUrl: cleanUrl(values.CAMO_URL, 'https://camo.tangled.sh')
});

export const getConfig = (): WebConfig => resolveConfig(env as WebConfigEnv);

export const getPublicConfig = (): PublicWebConfig => getConfig();
