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

export interface ListPredictionMarketsRequest {
  pageSize: number;
  cursor: string;
  category: string;
  query: string;
}

export interface ListPredictionMarketsResponse {
  markets: PredictionMarket[];
  pagination?: PaginationResponse;
  fetchedAt: number;
  dataAvailable: boolean;
}

export interface PredictionMarket {
  id: string;
  title: string;
  yesPrice: number;
  volume: number;
  url: string;
  closesAt: number;
  category: string;
  source: MarketSource;
}

export interface PaginationResponse {
  nextCursor: string;
  totalCount: number;
}

export type MarketSource = "MARKET_SOURCE_UNSPECIFIED" | "MARKET_SOURCE_POLYMARKET" | "MARKET_SOURCE_KALSHI";

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 PredictionServiceClientOptions {
  fetch?: typeof fetch;
  defaultHeaders?: Record<string, string>;
}

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

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

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

  async listPredictionMarkets(req: ListPredictionMarketsRequest, options?: PredictionServiceCallOptions): Promise<ListPredictionMarketsResponse> {
    let path = "/api/prediction/v1/list-prediction-markets";
    const params = new URLSearchParams();
    if (req.pageSize != null && req.pageSize !== 0) params.set("page_size", String(req.pageSize));
    if (req.cursor != null && req.cursor !== "") params.set("cursor", String(req.cursor));
    if (req.category != null && req.category !== "") params.set("category", String(req.category));
    if (req.query != null && req.query !== "") params.set("query", String(req.query));
    const url = this.baseURL + path + (params.toString() ? "?" + params.toString() : "");

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

    const resp = await this.fetchFn(url, {
      method: "GET",
      headers,
      signal: options?.signal,
    });

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

    return await resp.json() as ListPredictionMarketsResponse;
  }

  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);
  }
}

