/** Workspace API client. */

import { apiClient } from "./client";
import type {
	Workspace,
	CreateWorkspaceRequest,
	SyncResult,
} from "../types/workspace";

function workspaceUrl(projectId: string, repoId: string, workspaceId?: string) {
	const base = `/projects/${projectId}/repositories/${repoId}/workspaces`;
	return workspaceId ? `${base}/${workspaceId}` : `${base}/`;
}

export async function listWorkspaces(
	projectId: string,
	repoId: string,
): Promise<Workspace[]> {
	const response = await apiClient.get<Workspace[]>(
		workspaceUrl(projectId, repoId),
	);
	return response.data;
}

export async function listAllWorkspaces(): Promise<Workspace[]> {
	const response = await apiClient.get<Workspace[]>("/workspaces/");
	return response.data;
}

export async function createWorkspace(
	projectId: string,
	repoId: string,
	data: CreateWorkspaceRequest,
): Promise<Workspace> {
	const response = await apiClient.post<Workspace>(
		workspaceUrl(projectId, repoId),
		data,
	);
	return response.data;
}

export async function createWorkspaceTopLevel(
	data: CreateWorkspaceRequest & { repo_id: string },
): Promise<Workspace> {
	const response = await apiClient.post<Workspace>("/workspaces/", data);
	return response.data;
}

export async function getWorkspace(
	projectId: string,
	repoId: string,
	workspaceId: string,
): Promise<Workspace> {
	const response = await apiClient.get<Workspace>(
		workspaceUrl(projectId, repoId, workspaceId),
	);
	return response.data;
}

export async function updateWorkspace(
	projectId: string,
	repoId: string,
	workspaceId: string,
	data: Partial<CreateWorkspaceRequest>,
): Promise<Workspace> {
	const response = await apiClient.patch<Workspace>(
		workspaceUrl(projectId, repoId, workspaceId),
		data,
	);
	return response.data;
}

export async function deleteWorkspace(
	workspaceId: string,
	force = false,
): Promise<{ status: string }> {
	const response = await apiClient.delete<{ status: string }>(
		`/workspaces/${workspaceId}?force=${force}`,
	);
	return response.data;
}

export async function syncWorkspace(
	projectId: string,
	repoId: string,
	workspaceId: string,
): Promise<SyncResult> {
	const response = await apiClient.post<SyncResult>(
		`${workspaceUrl(projectId, repoId, workspaceId)}/sync`,
	);
	return response.data;
}
