/** Hook for workspace git operations. */

import { useCallback, useEffect, useState } from "react";
import {
	getGitStatus,
	getGitBranches,
	gitCommit,
	gitPush,
	gitPull,
	gitFetch,
	gitCheckout,
	getGitHistory,
	type GitStatus,
	type Commit,
} from "../api/workspace-git";

export interface UseWorkspaceGitResult {
	status: GitStatus | null;
	branches: string[];
	currentBranch: string;
	history: Commit[];
	loading: boolean;
	error: string | null;
	refresh: () => Promise<void>;
	commit: (message: string) => Promise<void>;
	push: () => Promise<void>;
	pull: () => Promise<void>;
	fetch: () => Promise<void>;
	checkout: (branch: string) => Promise<void>;
}

export function useWorkspaceGit(workspaceId: string): UseWorkspaceGitResult {
	const [status, setStatus] = useState<GitStatus | null>(null);
	const [branches, setBranches] = useState<string[]>([]);
	const [currentBranch, setCurrentBranch] = useState("");
	const [history, setHistory] = useState<Commit[]>([]);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState<string | null>(null);

	const refresh = useCallback(async () => {
		setLoading(true);
		setError(null);
		try {
			const [statusData, branchesData, historyData] = await Promise.all([
				getGitStatus(workspaceId),
				getGitBranches(workspaceId),
				getGitHistory(workspaceId),
			]);
			setStatus(statusData);
			setBranches(branchesData.branches);
			setCurrentBranch(branchesData.current_branch);
			setHistory(historyData);
		} catch (err) {
			setError(err instanceof Error ? err.message : "Failed to load git data");
		} finally {
			setLoading(false);
		}
	}, [workspaceId]);

	const commit = useCallback(
		async (message: string) => {
			await gitCommit(workspaceId, message);
			await refresh();
		},
		[workspaceId, refresh],
	);

	const push = useCallback(async () => {
		await gitPush(workspaceId);
		await refresh();
	}, [workspaceId, refresh]);

	const pull = useCallback(async () => {
		await gitPull(workspaceId);
		await refresh();
	}, [workspaceId, refresh]);

	const fetch = useCallback(async () => {
		await gitFetch(workspaceId);
		await refresh();
	}, [workspaceId, refresh]);

	const checkout = useCallback(
		async (branch: string) => {
			await gitCheckout(workspaceId, branch);
			await refresh();
		},
		[workspaceId, refresh],
	);

	useEffect(() => {
		refresh();
	}, [refresh]);

	return {
		status,
		branches,
		currentBranch,
		history,
		loading,
		error,
		refresh,
		commit,
		push,
		pull,
		fetch,
		checkout,
	};
}
