export interface EditorSettings {
	editor_command: string | null;
}

export interface ProjectSettings {
	default_qa: string;
	default_coder_model: string | null;
	max_coders: number | null;
	max_retries: number;
	base_branch: string | null;
	rate_limit_notifications: boolean;
	timezone: string | null;
	rendezvous: string | null;
	watcher_sweep_interval_secs: number;
	watcher_done_retention_secs: number;
}

export interface OpenFileResult {
	success: boolean;
}

const DEFAULT_API_BASE = "/api";

function buildApiUrl(path: string, baseUrl = DEFAULT_API_BASE): string {
	return `${baseUrl}${path}`;
}

async function requestJson<T>(
	path: string,
	options: RequestInit = {},
	baseUrl = DEFAULT_API_BASE,
): Promise<T> {
	const res = await fetch(buildApiUrl(path, baseUrl), {
		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 settingsApi = {
	getProjectSettings(baseUrl?: string): Promise<ProjectSettings> {
		return requestJson<ProjectSettings>("/settings", {}, baseUrl);
	},

	putProjectSettings(
		settings: ProjectSettings,
		baseUrl?: string,
	): Promise<ProjectSettings> {
		return requestJson<ProjectSettings>(
			"/settings",
			{ method: "PUT", body: JSON.stringify(settings) },
			baseUrl,
		);
	},

	getEditorCommand(baseUrl?: string): Promise<EditorSettings> {
		return requestJson<EditorSettings>("/settings/editor", {}, baseUrl);
	},

	setEditorCommand(
		command: string | null,
		baseUrl?: string,
	): Promise<EditorSettings> {
		return requestJson<EditorSettings>(
			"/settings/editor",
			{
				method: "PUT",
				body: JSON.stringify({ editor_command: command }),
			},
			baseUrl,
		);
	},

	openFile(
		path: string,
		line?: number,
		baseUrl?: string,
	): Promise<OpenFileResult> {
		const params = new URLSearchParams({ path });
		if (line !== undefined) {
			params.set("line", String(line));
		}
		return requestJson<OpenFileResult>(
			`/settings/open-file?${params.toString()}`,
			{ method: "POST" },
			baseUrl,
		);
	},
};
