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

export interface ListRadiationObservationsRequest {
  maxItems: number;
}

export interface ListRadiationObservationsResponse {
  observations: RadiationObservation[];
  fetchedAt: number;
  dataAvailable: boolean;
  epaCount: number;
  safecastCount: number;
  anomalyCount: number;
  elevatedCount: number;
  spikeCount: number;
  corroboratedCount: number;
  lowConfidenceCount: number;
  conflictingCount: number;
  convertedFromCpmCount: number;
}

export interface RadiationObservation {
  id: string;
  source: RadiationSource;
  locationName: string;
  country: string;
  location?: GeoCoordinates;
  value: number;
  unit: string;
  observedAt: number;
  freshness: RadiationFreshness;
  baselineValue: number;
  delta: number;
  zScore: number;
  severity: RadiationSeverity;
  contributingSources: RadiationSource[];
  confidence: RadiationConfidence;
  corroborated: boolean;
  conflictingSources: boolean;
  convertedFromCpm: boolean;
  sourceCount: number;
}

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

export type RadiationConfidence = "RADIATION_CONFIDENCE_UNSPECIFIED" | "RADIATION_CONFIDENCE_LOW" | "RADIATION_CONFIDENCE_MEDIUM" | "RADIATION_CONFIDENCE_HIGH";

export type RadiationFreshness = "RADIATION_FRESHNESS_UNSPECIFIED" | "RADIATION_FRESHNESS_LIVE" | "RADIATION_FRESHNESS_RECENT" | "RADIATION_FRESHNESS_HISTORICAL";

export type RadiationSeverity = "RADIATION_SEVERITY_UNSPECIFIED" | "RADIATION_SEVERITY_NORMAL" | "RADIATION_SEVERITY_ELEVATED" | "RADIATION_SEVERITY_SPIKE";

export type RadiationSource = "RADIATION_SOURCE_UNSPECIFIED" | "RADIATION_SOURCE_EPA_RADNET" | "RADIATION_SOURCE_SAFECAST";

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 RadiationServiceHandler {
  listRadiationObservations(ctx: ServerContext, req: ListRadiationObservationsRequest): Promise<ListRadiationObservationsResponse>;
}

export function createRadiationServiceRoutes(
  handler: RadiationServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/radiation/v1/list-radiation-observations",
      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: ListRadiationObservationsRequest = {
            maxItems: Number(params.get("max_items") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listRadiationObservations", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.listRadiationObservations(ctx, body);
          return new Response(JSON.stringify(result as ListRadiationObservationsResponse), {
            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" },
          });
        }
      },
    },
  ];
}

