// Code generated by protoc-gen-ts-client. DO NOT EDIT.
// source: worldmonitor/batch/v1/service.proto

export interface ExecuteBatchRequest {
  operations: BatchOperation[];
}

export interface BatchOperation {
  id: string;
  path: string;
}

export interface ExecuteBatchResponse {
  results: BatchOperationResult[];
  succeeded: number;
  failed: number;
}

export interface BatchOperationResult {
  id: string;
  status: number;
  body?: BatchOperationBody;
  error: string;
}

export interface BatchOperationBody {
}

export interface FieldViolation {
  field: string;
  description: string;
}

export class ValidationError extends Error {
  violations: FieldViolation[];

  constructor(violations: FieldViolation[]) {
    super("Validation failed");
    this.name = "ValidationError";
    this.violations = violations;
  }
}

export class ApiError extends Error {
  statusCode: number;
  body: string;

  constructor(statusCode: number, message: string, body: string) {
    super(message);
    this.name = "ApiError";
    this.statusCode = statusCode;
    this.body = body;
  }
}

export interface BatchServiceClientOptions {
  fetch?: typeof fetch;
  defaultHeaders?: Record<string, string>;
}

export interface BatchServiceCallOptions {
  headers?: Record<string, string>;
  signal?: AbortSignal;
}

export class BatchServiceClient {
  private baseURL: string;
  private fetchFn: typeof fetch;
  private defaultHeaders: Record<string, string>;

  constructor(baseURL: string, options?: BatchServiceClientOptions) {
    this.baseURL = baseURL.replace(/\/+$/, "");
    this.fetchFn = options?.fetch ?? globalThis.fetch;
    this.defaultHeaders = { ...options?.defaultHeaders };
  }

  async executeBatch(req: ExecuteBatchRequest, options?: BatchServiceCallOptions): Promise<ExecuteBatchResponse> {
    let path = "/api/batch/v1/execute";
    const url = this.baseURL + path;

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...this.defaultHeaders,
      ...options?.headers,
    };

    const resp = await this.fetchFn(url, {
      method: "POST",
      headers,
      body: JSON.stringify(req),
      signal: options?.signal,
    });

    if (!resp.ok) {
      return this.handleError(resp);
    }

    return await resp.json() as ExecuteBatchResponse;
  }

  private async handleError(resp: Response): Promise<never> {
    const body = await resp.text();
    if (resp.status === 400) {
      try {
        const parsed = JSON.parse(body);
        if (parsed.violations) {
          throw new ValidationError(parsed.violations);
        }
      } catch (e) {
        if (e instanceof ValidationError) throw e;
      }
    }
    throw new ApiError(resp.status, `Request failed with status ${resp.status}`, body);
  }
}

