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

export interface ListClimateAnomaliesRequest {
  pageSize: number;
  cursor: string;
  minSeverity: AnomalySeverity;
}

export interface ListClimateAnomaliesResponse {
  anomalies: ClimateAnomaly[];
  pagination?: PaginationResponse;
}

export interface ClimateAnomaly {
  zone: string;
  location?: GeoCoordinates;
  tempDelta: number;
  precipDelta: number;
  severity: AnomalySeverity;
  type: AnomalyType;
  period: string;
}

export interface GeoCoordinates {
  latitude: number;
  longitude: number;
}

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

export interface ListClimateDisastersRequest {
  pageSize: number;
  cursor: string;
}

export interface ListClimateDisastersResponse {
  disasters: ClimateDisaster[];
  pagination?: PaginationResponse;
}

export interface ClimateDisaster {
  id: string;
  type: string;
  name: string;
  country: string;
  countryCode: string;
  lat: number;
  lng: number;
  severity: string;
  startedAt: number;
  status: string;
  affectedPopulation: number;
  source: string;
  sourceUrl: string;
}

export interface GetCo2MonitoringRequest {
}

export interface GetCo2MonitoringResponse {
  monitoring?: Co2Monitoring;
}

export interface Co2Monitoring {
  currentPpm: number;
  yearAgoPpm: number;
  annualGrowthRate: number;
  preIndustrialBaseline: number;
  monthlyAverage: number;
  trend12m: Co2DataPoint[];
  methanePpb: number;
  nitrousOxidePpb: number;
  measuredAt: string;
  station: string;
}

export interface Co2DataPoint {
  month: string;
  ppm: number;
  anomaly: number;
}

export interface GetOceanIceDataRequest {
}

export interface GetOceanIceDataResponse {
  data?: OceanIceData;
}

export interface OceanIceData {
  arcticExtentMkm2: number;
  arcticExtentAnomalyMkm2: number;
  arcticTrend: string;
  seaLevelMmAbove1993: number;
  seaLevelAnnualRiseMm: number;
  ohc0700mZj: number;
  sstAnomalyC: number;
  measuredAt: number;
  iceTrend12m: IceTrendPoint[];
}

export interface IceTrendPoint {
  month: string;
  extentMkm2: number;
  anomalyMkm2: number;
}

export interface ListAirQualityDataRequest {
}

export interface ListAirQualityDataResponse {
  stations: AirQualityStation[];
  fetchedAt: number;
}

export interface AirQualityStation {
  city: string;
  countryCode: string;
  lat: number;
  lng: number;
  pm25: number;
  aqi: number;
  riskLevel: string;
  pollutant: string;
  measuredAt: number;
  source: string;
}

export interface ListClimateNewsRequest {
}

export interface ListClimateNewsResponse {
  items: ClimateNewsItem[];
  fetchedAt: number;
}

export interface ClimateNewsItem {
  id: string;
  title: string;
  url: string;
  sourceName: string;
  publishedAt: number;
  summary: string;
}

export type AnomalySeverity = "ANOMALY_SEVERITY_UNSPECIFIED" | "ANOMALY_SEVERITY_NORMAL" | "ANOMALY_SEVERITY_MODERATE" | "ANOMALY_SEVERITY_EXTREME";

export type AnomalyType = "ANOMALY_TYPE_UNSPECIFIED" | "ANOMALY_TYPE_WARM" | "ANOMALY_TYPE_COLD" | "ANOMALY_TYPE_WET" | "ANOMALY_TYPE_DRY" | "ANOMALY_TYPE_MIXED";

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

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

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

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

  async listClimateAnomalies(req: ListClimateAnomaliesRequest, options?: ClimateServiceCallOptions): Promise<ListClimateAnomaliesResponse> {
    let path = "/api/climate/v1/list-climate-anomalies";
    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.minSeverity != null && req.minSeverity !== "ANOMALY_SEVERITY_UNSPECIFIED") params.set("min_severity", String(req.minSeverity));
    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 ListClimateAnomaliesResponse;
  }

  async listClimateDisasters(req: ListClimateDisastersRequest, options?: ClimateServiceCallOptions): Promise<ListClimateDisastersResponse> {
    let path = "/api/climate/v1/list-climate-disasters";
    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));
    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 ListClimateDisastersResponse;
  }

  async getCo2Monitoring(_req: GetCo2MonitoringRequest, options?: ClimateServiceCallOptions): Promise<GetCo2MonitoringResponse> {
    let path = "/api/climate/v1/get-co2-monitoring";
    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: "GET",
      headers,
      signal: options?.signal,
    });

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

    return await resp.json() as GetCo2MonitoringResponse;
  }

  async getOceanIceData(_req: GetOceanIceDataRequest, options?: ClimateServiceCallOptions): Promise<GetOceanIceDataResponse> {
    let path = "/api/climate/v1/get-ocean-ice-data";
    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: "GET",
      headers,
      signal: options?.signal,
    });

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

    return await resp.json() as GetOceanIceDataResponse;
  }

  async listAirQualityData(_req: ListAirQualityDataRequest, options?: ClimateServiceCallOptions): Promise<ListAirQualityDataResponse> {
    let path = "/api/climate/v1/list-air-quality-data";
    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: "GET",
      headers,
      signal: options?.signal,
    });

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

    return await resp.json() as ListAirQualityDataResponse;
  }

  async listClimateNews(_req: ListClimateNewsRequest, options?: ClimateServiceCallOptions): Promise<ListClimateNewsResponse> {
    let path = "/api/climate/v1/list-climate-news";
    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: "GET",
      headers,
      signal: options?.signal,
    });

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

    return await resp.json() as ListClimateNewsResponse;
  }

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

