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

export interface ListThermalEscalationsRequest {
  maxItems: number;
}

export interface ListThermalEscalationsResponse {
  fetchedAt: string;
  observationWindowHours: number;
  sourceVersion: string;
  clusters: ThermalEscalationCluster[];
  summary?: ThermalEscalationSummary;
  dataAvailable: boolean;
}

export interface ThermalEscalationCluster {
  id: string;
  centroid?: GeoCoordinates;
  countryCode: string;
  countryName: string;
  regionLabel: string;
  firstDetectedAt: string;
  lastDetectedAt: string;
  observationCount: number;
  uniqueSourceCount: number;
  maxBrightness: number;
  avgBrightness: number;
  maxFrp: number;
  totalFrp: number;
  nightDetectionShare: number;
  baselineExpectedCount: number;
  baselineExpectedFrp: number;
  countDelta: number;
  frpDelta: number;
  zScore: number;
  persistenceHours: number;
  status: ThermalStatus;
  context: ThermalContext;
  confidence: ThermalConfidence;
  strategicRelevance: ThermalStrategicRelevance;
  nearbyAssets: string[];
  narrativeFlags: string[];
}

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

export interface ThermalEscalationSummary {
  clusterCount: number;
  elevatedCount: number;
  spikeCount: number;
  persistentCount: number;
  conflictAdjacentCount: number;
  highRelevanceCount: number;
}

export type ThermalConfidence = "THERMAL_CONFIDENCE_UNSPECIFIED" | "THERMAL_CONFIDENCE_LOW" | "THERMAL_CONFIDENCE_MEDIUM" | "THERMAL_CONFIDENCE_HIGH";

export type ThermalContext = "THERMAL_CONTEXT_UNSPECIFIED" | "THERMAL_CONTEXT_WILDLAND" | "THERMAL_CONTEXT_URBAN_EDGE" | "THERMAL_CONTEXT_INDUSTRIAL" | "THERMAL_CONTEXT_ENERGY_ADJACENT" | "THERMAL_CONTEXT_CONFLICT_ADJACENT" | "THERMAL_CONTEXT_LOGISTICS_ADJACENT" | "THERMAL_CONTEXT_MIXED";

export type ThermalStatus = "THERMAL_STATUS_UNSPECIFIED" | "THERMAL_STATUS_NORMAL" | "THERMAL_STATUS_ELEVATED" | "THERMAL_STATUS_SPIKE" | "THERMAL_STATUS_PERSISTENT";

export type ThermalStrategicRelevance = "THERMAL_RELEVANCE_UNSPECIFIED" | "THERMAL_RELEVANCE_LOW" | "THERMAL_RELEVANCE_MEDIUM" | "THERMAL_RELEVANCE_HIGH";

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 ThermalServiceHandler {
  listThermalEscalations(ctx: ServerContext, req: ListThermalEscalationsRequest): Promise<ListThermalEscalationsResponse>;
}

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

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

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

