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

export interface GetDisplacementSummaryRequest {
  year: number;
  countryLimit: number;
  flowLimit: number;
}

export interface GetDisplacementSummaryResponse {
  summary?: DisplacementSummary;
}

export interface DisplacementSummary {
  year: number;
  globalTotals?: GlobalDisplacementTotals;
  countries: CountryDisplacement[];
  topFlows: DisplacementFlow[];
}

export interface GlobalDisplacementTotals {
  refugees: number;
  asylumSeekers: number;
  idps: number;
  stateless: number;
  total: number;
}

export interface CountryDisplacement {
  code: string;
  name: string;
  refugees: number;
  asylumSeekers: number;
  idps: number;
  stateless: number;
  totalDisplaced: number;
  hostRefugees: number;
  hostAsylumSeekers: number;
  hostTotal: number;
  location?: GeoCoordinates;
}

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

export interface DisplacementFlow {
  originCode: string;
  originName: string;
  asylumCode: string;
  asylumName: string;
  refugees: number;
  originLocation?: GeoCoordinates;
  asylumLocation?: GeoCoordinates;
}

export interface GetPopulationExposureRequest {
  mode: string;
  lat: number;
  lon: number;
  radius: number;
}

export interface GetPopulationExposureResponse {
  success: boolean;
  countries: CountryPopulationEntry[];
  exposure?: ExposureResult;
}

export interface CountryPopulationEntry {
  code: string;
  name: string;
  population: number;
  densityPerKm2: number;
}

export interface ExposureResult {
  exposedPopulation: number;
  exposureRadiusKm: number;
  nearestCountry: string;
  densityPerKm2: number;
}

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 DisplacementServiceHandler {
  getDisplacementSummary(ctx: ServerContext, req: GetDisplacementSummaryRequest): Promise<GetDisplacementSummaryResponse>;
  getPopulationExposure(ctx: ServerContext, req: GetPopulationExposureRequest): Promise<GetPopulationExposureResponse>;
}

export function createDisplacementServiceRoutes(
  handler: DisplacementServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/displacement/v1/get-displacement-summary",
      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: GetDisplacementSummaryRequest = {
            year: Number(params.get("year") ?? "0"),
            countryLimit: Number(params.get("country_limit") ?? "0"),
            flowLimit: Number(params.get("flow_limit") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getDisplacementSummary", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getDisplacementSummary(ctx, body);
          return new Response(JSON.stringify(result as GetDisplacementSummaryResponse), {
            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/displacement/v1/get-population-exposure",
      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: GetPopulationExposureRequest = {
            mode: params.get("mode") ?? "",
            lat: Number(params.get("lat") ?? "0"),
            lon: Number(params.get("lon") ?? "0"),
            radius: Number(params.get("radius") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getPopulationExposure", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

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

