import { apiGet, apiPost } from "./client";
import { apiUrl } from "./base";
import type { SessionState } from "../types/message";
import type { SessionHistoryPayload, SessionSummary } from "../types/session";

export function fetchSessions(): Promise<{ sessions: SessionSummary[] }> {
	return apiGet("/api/sessions");
}

export function fetchSessionHistory(path: string): Promise<SessionHistoryPayload> {
	return apiPost("/api/sessions/history", { path });
}

export async function activateSessionBackend(path: string): Promise<SessionState | null> {
	const activateRes = await fetch(apiUrl("/api/sessions/activate"), {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({ path }),
	});
	const activateData = (await activateRes.json().catch(() => ({}))) as {
		error?: string;
		state?: SessionState;
	};
	if (activateRes.ok && !activateData.error) {
		return activateData.state ?? null;
	}

	const activateError = activateData.error || activateRes.statusText || "Unknown error";
	if (activateRes.status !== 404 && !/not found/i.test(activateError)) {
		throw new Error(activateError);
	}

	const fallbackRes = await fetch(apiUrl("/api/sessions/load"), {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({ path }),
	});
	const fallbackData = (await fallbackRes.json().catch(() => ({}))) as { error?: string };
	if (!fallbackRes.ok || fallbackData.error) {
		throw new Error(fallbackData.error || fallbackRes.statusText);
	}
	return null;
}

export function loadSession(path: string): Promise<{ ok?: boolean; error?: string }> {
	return apiPost("/api/sessions/load", { path });
}

export function deleteSession(path: string): Promise<{ ok?: boolean }> {
	return apiPost("/api/sessions/delete", { path });
}

export function renameSession(path: string, name: string): Promise<{ ok?: boolean }> {
	return apiPost("/api/sessions/name", { path, name });
}

export function setSessionPinned(path: string, pinned: boolean): Promise<{ ok?: boolean; pinned?: boolean; pinnedPaths?: string[] }> {
	return apiPost("/api/sessions/pin", { path, pinned });
}
