// Code generated by protoc-gen-ts-server. 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;
  dataAvailable: boolean;
}

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 ServerContext {
  request: Request;
  pathParams: Record<string, string>;
  headers: Record<string, string>;
}

export interface ServerOptions {
  onError?: (error: unknown, req: Request) => Response | Promise<Response>;
  validateRequest?: (methodName: string, body: unknown) => FieldViolation[] | undefined;
}

export interface RouteDescriptor {
  method: string;
  path: string;
  handler: (req: Request) => Promise<Response>;
}

export interface ClimateServiceHandler {
  listClimateAnomalies(ctx: ServerContext, req: ListClimateAnomaliesRequest): Promise<ListClimateAnomaliesResponse>;
  listClimateDisasters(ctx: ServerContext, req: ListClimateDisastersRequest): Promise<ListClimateDisastersResponse>;
  getCo2Monitoring(ctx: ServerContext, req: GetCo2MonitoringRequest): Promise<GetCo2MonitoringResponse>;
  getOceanIceData(ctx: ServerContext, req: GetOceanIceDataRequest): Promise<GetOceanIceDataResponse>;
  listAirQualityData(ctx: ServerContext, req: ListAirQualityDataRequest): Promise<ListAirQualityDataResponse>;
  listClimateNews(ctx: ServerContext, req: ListClimateNewsRequest): Promise<ListClimateNewsResponse>;
}

export function createClimateServiceRoutes(
  handler: ClimateServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/climate/v1/list-climate-anomalies",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: ListClimateAnomaliesRequest = {
            pageSize: Number(params.get("page_size") ?? "0"),
            cursor: params.get("cursor") ?? "",
            minSeverity: (params.get("min_severity") ?? "ANOMALY_SEVERITY_UNSPECIFIED") as AnomalySeverity,
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listClimateAnomalies", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.listClimateAnomalies(ctx, body);
          return new Response(JSON.stringify(result as ListClimateAnomaliesResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/climate/v1/list-climate-disasters",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: ListClimateDisastersRequest = {
            pageSize: Number(params.get("page_size") ?? "0"),
            cursor: params.get("cursor") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listClimateDisasters", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.listClimateDisasters(ctx, body);
          return new Response(JSON.stringify(result as ListClimateDisastersResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/climate/v1/get-co2-monitoring",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as GetCo2MonitoringRequest;

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getCo2Monitoring(ctx, body);
          return new Response(JSON.stringify(result as GetCo2MonitoringResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/climate/v1/get-ocean-ice-data",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as GetOceanIceDataRequest;

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getOceanIceData(ctx, body);
          return new Response(JSON.stringify(result as GetOceanIceDataResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/climate/v1/list-air-quality-data",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as ListAirQualityDataRequest;

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.listAirQualityData(ctx, body);
          return new Response(JSON.stringify(result as ListAirQualityDataResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/climate/v1/list-climate-news",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as ListClimateNewsRequest;

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.listClimateNews(ctx, body);
          return new Response(JSON.stringify(result as ListClimateNewsResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
  ];
}

