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

export interface RouteIntelligenceRequest {
  fromIso2: string;
  toIso2: string;
  cargoType: string;
  hs2: string;
}

export interface RouteIntelligenceResponse {
  fromIso2: string;
  toIso2: string;
  cargoType: string;
  hs2: string;
  primaryRouteId: string;
  chokepointExposures: ChokepointExposure[];
  bypassOptions: BypassOption[];
  warRiskTier: string;
  disruptionScore: number;
  fetchedAt: string;
}

export interface ChokepointExposure {
  chokepointId: string;
  chokepointName: string;
  exposurePct: number;
}

export interface BypassOption {
  id: string;
  name: string;
  type: string;
  addedTransitDays: number;
  addedCostMultiplier: number;
  activationThreshold: string;
}

export interface RegisterWebhookRequest {
  callbackUrl: string;
  chokepointIds: string[];
  alertThreshold: number;
}

export interface RegisterWebhookResponse {
  subscriberId: string;
  secret: string;
}

export interface ListWebhooksRequest {
}

export interface ListWebhooksResponse {
  webhooks: WebhookSummary[];
}

export interface WebhookSummary {
  subscriberId: string;
  callbackUrl: string;
  chokepointIds: string[];
  alertThreshold: number;
  createdAt: string;
  active: boolean;
}

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 ShippingV2ServiceHandler {
  routeIntelligence(ctx: ServerContext, req: RouteIntelligenceRequest): Promise<RouteIntelligenceResponse>;
  registerWebhook(ctx: ServerContext, req: RegisterWebhookRequest): Promise<RegisterWebhookResponse>;
  listWebhooks(ctx: ServerContext, req: ListWebhooksRequest): Promise<ListWebhooksResponse>;
}

export function createShippingV2ServiceRoutes(
  handler: ShippingV2ServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/v2/shipping/route-intelligence",
      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: RouteIntelligenceRequest = {
            fromIso2: params.get("fromIso2") ?? "",
            toIso2: params.get("toIso2") ?? "",
            cargoType: params.get("cargoType") ?? "",
            hs2: params.get("hs2") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("routeIntelligence", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.routeIntelligence(ctx, body);
          return new Response(JSON.stringify(result as RouteIntelligenceResponse), {
            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: "POST",
      path: "/api/v2/shipping/webhooks",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = await req.json() as RegisterWebhookRequest;
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("registerWebhook", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.registerWebhook(ctx, body);
          return new Response(JSON.stringify(result as RegisterWebhookResponse), {
            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/v2/shipping/webhooks",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as ListWebhooksRequest;

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

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

