/**
 * WS-RPC client for editor and project settings.
 */
import { rpcCall } from "./rpc";
import type {
	EditorSettingsResult,
	OkResult,
	OpenFileParams,
	ProjectSettingsPayload,
	PutEditorParams,
} from "./rpcContract";

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;
}

export const settingsApi = {
	getProjectSettings(_baseUrl?: string): Promise<ProjectSettings> {
		return rpcCall<ProjectSettings>("settings.get_project");
	},

	async putProjectSettings(
		settings: ProjectSettings,
		_baseUrl?: string,
	): Promise<ProjectSettings> {
		const params: ProjectSettingsPayload = settings;
		return rpcCall<ProjectSettingsPayload>("settings.put_project", params);
	},

	getEditorCommand(_baseUrl?: string): Promise<EditorSettings> {
		return rpcCall<EditorSettings>("settings.get_editor");
	},

	async setEditorCommand(
		command: string | null,
		_baseUrl?: string,
	): Promise<EditorSettings> {
		const params: PutEditorParams = { editor_command: command };
		const r = await rpcCall<EditorSettingsResult>("settings.put_editor", params);
		return { editor_command: r.editor_command };
	},

	async openFile(
		path: string,
		line?: number,
		_baseUrl?: string,
	): Promise<OpenFileResult> {
		const params: OpenFileParams = { path, line: line ?? null };
		const r = await rpcCall<OkResult>("settings.open_file", params);
		return { success: r.ok };
	},
};
