/** Workspace git API client. */

import { apiClient } from "./client";

export interface GitStatus {
	branch: string;
	modified: string[];
	added: string[];
	deleted: string[];
	untracked: string[];
	ahead: number;
	behind: number;
}

export interface Commit {
	hash: string;
	message: string;
	author: string;
	date: string;
}

export async function getGitStatus(workspaceId: string): Promise<GitStatus> {
	const response = await apiClient.get<GitStatus>(
		`/workspaces/${workspaceId}/git/status`,
	);
	return response.data;
}

export async function getGitBranches(
	workspaceId: string,
): Promise<{ branches: string[]; current_branch: string }> {
	const response = await apiClient.get<{
		branches: string[];
		current_branch: string;
	}>(`/workspaces/${workspaceId}/git/branches`);
	return response.data;
}

export async function gitCommit(
	workspaceId: string,
	message: string,
): Promise<void> {
	await apiClient.post(`/workspaces/${workspaceId}/git/commit`, { message });
}

export async function gitPush(workspaceId: string): Promise<void> {
	await apiClient.post(`/workspaces/${workspaceId}/git/push`);
}

export async function gitPull(workspaceId: string): Promise<void> {
	await apiClient.post(`/workspaces/${workspaceId}/git/pull`);
}

export async function gitFetch(workspaceId: string): Promise<void> {
	await apiClient.post(`/workspaces/${workspaceId}/git/fetch`);
}

export async function gitCheckout(
	workspaceId: string,
	branch: string,
): Promise<void> {
	await apiClient.post(`/workspaces/${workspaceId}/git/checkout`, { branch });
}

export async function getGitHistory(
	workspaceId: string,
	path?: string,
	limit: number = 50,
): Promise<Commit[]> {
	const response = await apiClient.get<{ commits: Commit[] }>(
		`/workspaces/${workspaceId}/git/history`,
		{ params: { path, limit } },
	);
	return response.data.commits;
}
