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

export interface ListUnrestEventsRequest {
  start: number;
  end: number;
  pageSize: number;
  cursor: string;
  country: string;
  minSeverity: SeverityLevel;
  neLat: number;
  neLon: number;
  swLat: number;
  swLon: number;
}

export interface ListUnrestEventsResponse {
  events: UnrestEvent[];
  clusters: UnrestCluster[];
  pagination?: PaginationResponse;
}

export interface UnrestEvent {
  id: string;
  title: string;
  summary: string;
  eventType: UnrestEventType;
  city: string;
  country: string;
  region: string;
  location?: GeoCoordinates;
  occurredAt: number;
  severity: SeverityLevel;
  fatalities: number;
  sources: string[];
  sourceType: UnrestSourceType;
  tags: string[];
  actors: string[];
  confidence: ConfidenceLevel;
}

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

export interface UnrestCluster {
  id: string;
  country: string;
  region: string;
  eventCount: number;
  events: UnrestEvent[];
  severity: SeverityLevel;
  startAt: number;
  endAt: number;
  primaryCause: string;
}

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

export type SeverityLevel = "SEVERITY_LEVEL_UNSPECIFIED" | "SEVERITY_LEVEL_LOW" | "SEVERITY_LEVEL_MEDIUM" | "SEVERITY_LEVEL_HIGH";

export type ConfidenceLevel = "CONFIDENCE_LEVEL_UNSPECIFIED" | "CONFIDENCE_LEVEL_LOW" | "CONFIDENCE_LEVEL_MEDIUM" | "CONFIDENCE_LEVEL_HIGH";

export type UnrestEventType = "UNREST_EVENT_TYPE_UNSPECIFIED" | "UNREST_EVENT_TYPE_PROTEST" | "UNREST_EVENT_TYPE_RIOT" | "UNREST_EVENT_TYPE_STRIKE" | "UNREST_EVENT_TYPE_DEMONSTRATION" | "UNREST_EVENT_TYPE_CIVIL_UNREST";

export type UnrestSourceType = "UNREST_SOURCE_TYPE_UNSPECIFIED" | "UNREST_SOURCE_TYPE_ACLED" | "UNREST_SOURCE_TYPE_GDELT" | "UNREST_SOURCE_TYPE_RSS";

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 UnrestServiceHandler {
  listUnrestEvents(ctx: ServerContext, req: ListUnrestEventsRequest): Promise<ListUnrestEventsResponse>;
}

export function createUnrestServiceRoutes(
  handler: UnrestServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/unrest/v1/list-unrest-events",
      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: ListUnrestEventsRequest = {
            start: Number(params.get("start") ?? "0"),
            end: Number(params.get("end") ?? "0"),
            pageSize: Number(params.get("page_size") ?? "0"),
            cursor: params.get("cursor") ?? "",
            country: params.get("country") ?? "",
            minSeverity: params.get("min_severity") ?? "",
            neLat: Number(params.get("ne_lat") ?? "0"),
            neLon: Number(params.get("ne_lon") ?? "0"),
            swLat: Number(params.get("sw_lat") ?? "0"),
            swLon: Number(params.get("sw_lon") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listUnrestEvents", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

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

