import { API_BASE_URL } from "@/lib/config";

const BASE_URL = API_BASE_URL;

// --- Types ---

export type WorkspaceInfo = {
  id: string;
  name: string;
  path: string;
  description: string;
  created_at: string;
  is_active: boolean;
};

export type FileTreeNode = {
  name: string;
  path: string;
  type: "file" | "dir";
  size: number;
  children?: FileTreeNode[] | null;
};

export type FileContent = {
  path: string;
  content: string;
  total_lines: number;
  offset: number;
  limit: number | null;
};

// --- Workspace CRUD ---

export async function fetchWorkspaces(): Promise<WorkspaceInfo[]> {
  const res = await fetch(`${BASE_URL}/api/workspace/`);
  if (!res.ok) throw new Error("Failed to fetch workspaces");
  return res.json();
}

export async function fetchWorkspace(id: string): Promise<WorkspaceInfo> {
  const res = await fetch(`${BASE_URL}/api/workspace/${id}`);
  if (!res.ok) throw new Error("Failed to fetch workspace");
  return res.json();
}

export async function createWorkspace(
  name: string,
  path: string,
  description: string = ""
): Promise<WorkspaceInfo> {
  const res = await fetch(`${BASE_URL}/api/workspace/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, path, description }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to create workspace");
  }
  return res.json();
}

export async function updateWorkspace(
  id: string,
  updates: { name?: string; description?: string }
): Promise<WorkspaceInfo> {
  const res = await fetch(`${BASE_URL}/api/workspace/${id}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  if (!res.ok) throw new Error("Failed to update workspace");
  return res.json();
}

export async function deleteWorkspace(id: string): Promise<void> {
  const res = await fetch(`${BASE_URL}/api/workspace/${id}`, {
    method: "DELETE",
  });
  if (!res.ok) throw new Error("Failed to delete workspace");
}

export async function activateWorkspace(id: string): Promise<WorkspaceInfo> {
  const res = await fetch(`${BASE_URL}/api/workspace/${id}/activate`, {
    method: "POST",
  });
  if (!res.ok) throw new Error("Failed to activate workspace");
  return res.json();
}

export async function deactivateWorkspace(): Promise<void> {
  const res = await fetch(`${BASE_URL}/api/workspace/deactivate`, {
    method: "POST",
  });
  if (!res.ok) throw new Error("Failed to deactivate workspace");
}

// --- File Operations ---

export async function fetchFileTree(
  id: string,
  path: string = ".",
  maxDepth: number = 3
): Promise<FileTreeNode[]> {
  const params = new URLSearchParams({ path, max_depth: String(maxDepth) });
  const res = await fetch(`${BASE_URL}/api/workspace/${id}/tree?${params}`);
  if (!res.ok) throw new Error("Failed to fetch file tree");
  return res.json();
}

export async function fetchFileContent(
  id: string,
  path: string,
  offset: number = 0,
  limit?: number
): Promise<FileContent> {
  const params = new URLSearchParams({ path, offset: String(offset) });
  if (limit !== undefined) params.set("limit", String(limit));
  const res = await fetch(`${BASE_URL}/api/workspace/${id}/file?${params}`);
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to fetch file");
  }
  return res.json();
}

// --- Raw File URLs ---

export function getFileRawUrl(workspaceId: string, path: string): string {
  const params = new URLSearchParams({ path });
  return `${BASE_URL}/api/workspace/${workspaceId}/raw?${params}`;
}

export function getFileDownloadUrl(workspaceId: string, path: string): string {
  const params = new URLSearchParams({ path, download: "true" });
  return `${BASE_URL}/api/workspace/${workspaceId}/raw?${params}`;
}
