export interface BotConfig {
	transport: string | null;
	enabled: boolean | null;
	homeserver: string | null;
	username: string | null;
	password: string | null;
	room_ids: string[] | null;
	slack_bot_token: string | null;
	slack_signing_secret: string | null;
	slack_channel_ids: string[] | null;
}

const DEFAULT_API_BASE = "/api";

async function requestJson<T>(
	path: string,
	options: RequestInit = {},
	baseUrl = DEFAULT_API_BASE,
): Promise<T> {
	const res = await fetch(`${baseUrl}${path}`, {
		headers: { "Content-Type": "application/json", ...(options.headers ?? {}) },
		...options,
	});
	if (!res.ok) {
		const text = await res.text();
		throw new Error(text || `Request failed (${res.status})`);
	}
	return res.json() as Promise<T>;
}

export const botConfigApi = {
	getConfig(baseUrl?: string): Promise<BotConfig> {
		return requestJson<BotConfig>("/bot/config", {}, baseUrl);
	},

	saveConfig(config: BotConfig, baseUrl?: string): Promise<BotConfig> {
		return requestJson<BotConfig>(
			"/bot/config",
			{ method: "PUT", body: JSON.stringify(config) },
			baseUrl,
		);
	},
};
