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

export interface GetVesselSnapshotRequest {
  neLat: number;
  neLon: number;
  swLat: number;
  swLon: number;
  includeCandidates: boolean;
  includeTankers: boolean;
}

export interface GetVesselSnapshotResponse {
  snapshot?: VesselSnapshot;
  fetchedAt: number;
  dataAvailable: boolean;
}

export interface VesselSnapshot {
  snapshotAt: number;
  densityZones: AisDensityZone[];
  disruptions: AisDisruption[];
  sequence: number;
  status?: AisSnapshotStatus;
  candidateReports: SnapshotCandidateReport[];
  tankerReports: SnapshotCandidateReport[];
}

export interface AisDensityZone {
  id: string;
  name: string;
  location?: GeoCoordinates;
  intensity: number;
  deltaPct: number;
  shipsPerDay: number;
  note: string;
}

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

export interface AisDisruption {
  id: string;
  name: string;
  type: AisDisruptionType;
  location?: GeoCoordinates;
  severity: AisDisruptionSeverity;
  changePct: number;
  windowHours: number;
  darkShips: number;
  vesselCount: number;
  region: string;
  description: string;
}

export interface AisSnapshotStatus {
  connected: boolean;
  vessels: number;
  messages: number;
}

export interface SnapshotCandidateReport {
  mmsi: string;
  name: string;
  lat: number;
  lon: number;
  shipType: number;
  heading: number;
  speed: number;
  course: number;
  timestamp: number;
}

export interface ListNavigationalWarningsRequest {
  pageSize: number;
  cursor: string;
  area: string;
}

export interface ListNavigationalWarningsResponse {
  warnings: NavigationalWarning[];
  pagination?: PaginationResponse;
}

export interface NavigationalWarning {
  id: string;
  title: string;
  text: string;
  area: string;
  location?: GeoCoordinates;
  issuedAt: number;
  expiresAt: number;
  authority: string;
}

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

export type AisDisruptionSeverity = "AIS_DISRUPTION_SEVERITY_UNSPECIFIED" | "AIS_DISRUPTION_SEVERITY_LOW" | "AIS_DISRUPTION_SEVERITY_ELEVATED" | "AIS_DISRUPTION_SEVERITY_HIGH";

export type AisDisruptionType = "AIS_DISRUPTION_TYPE_UNSPECIFIED" | "AIS_DISRUPTION_TYPE_GAP_SPIKE" | "AIS_DISRUPTION_TYPE_CHOKEPOINT_CONGESTION";

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 MaritimeServiceHandler {
  getVesselSnapshot(ctx: ServerContext, req: GetVesselSnapshotRequest): Promise<GetVesselSnapshotResponse>;
  listNavigationalWarnings(ctx: ServerContext, req: ListNavigationalWarningsRequest): Promise<ListNavigationalWarningsResponse>;
}

export function createMaritimeServiceRoutes(
  handler: MaritimeServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/maritime/v1/get-vessel-snapshot",
      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: GetVesselSnapshotRequest = {
            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"),
            includeCandidates: params.get("include_candidates") === "true",
            includeTankers: params.get("include_tankers") === "true",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getVesselSnapshot", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getVesselSnapshot(ctx, body);
          return new Response(JSON.stringify(result as GetVesselSnapshotResponse), {
            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/maritime/v1/list-navigational-warnings",
      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: ListNavigationalWarningsRequest = {
            pageSize: Number(params.get("page_size") ?? "0"),
            cursor: params.get("cursor") ?? "",
            area: params.get("area") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listNavigationalWarnings", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

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

