import { apiFetch } from "./auth";

export interface FileEntry {
  name: string;
  path: string;
  isDir: boolean;
  size: number;
  modifiedAt?: string;
}

export interface ListFilesResponse {
  path: string;
  entries: FileEntry[];
}

export interface FileContentResponse {
  path: string;
  content: string;
  truncated?: boolean;
  version?: number;
}

export interface WriteFilePayload {
  path: string;
  content: string;
  version?: number;
}

export async function listFiles(
  serverId: string,
  path = "",
): Promise<ListFilesResponse> {
  const params = new URLSearchParams();
  if (path) {
    params.set("path", path);
  }
  const query = params.toString();
  return apiFetch<ListFilesResponse>(
    `/servers/${serverId}/files${query ? `?${query}` : ""}`,
  );
}

export async function readFile(
  serverId: string,
  path: string,
): Promise<FileContentResponse> {
  const params = new URLSearchParams({ path });
  return apiFetch<FileContentResponse>(
    `/servers/${serverId}/files/content?${params.toString()}`,
  );
}

export async function writeFile(
  serverId: string,
  payload: WriteFilePayload,
): Promise<FileContentResponse> {
  return apiFetch<FileContentResponse>(`/servers/${serverId}/files/content`, {
    method: "PUT",
    body: JSON.stringify(payload),
  });
}
