// Code generated by protoc-gen-ts-client. 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 ShippingV2ServiceClientOptions {
  fetch?: typeof fetch;
  defaultHeaders?: Record<string, string>;
}

export interface ShippingV2ServiceCallOptions {
  headers?: Record<string, string>;
  signal?: AbortSignal;
}

export class ShippingV2ServiceClient {
  private baseURL: string;
  private fetchFn: typeof fetch;
  private defaultHeaders: Record<string, string>;

  constructor(baseURL: string, options?: ShippingV2ServiceClientOptions) {
    this.baseURL = baseURL.replace(/\/+$/, "");
    this.fetchFn = options?.fetch ?? globalThis.fetch;
    this.defaultHeaders = { ...options?.defaultHeaders };
  }

  async routeIntelligence(req: RouteIntelligenceRequest, options?: ShippingV2ServiceCallOptions): Promise<RouteIntelligenceResponse> {
    let path = "/api/v2/shipping/route-intelligence";
    const params = new URLSearchParams();
    if (req.fromIso2 != null && req.fromIso2 !== "") params.set("fromIso2", String(req.fromIso2));
    if (req.toIso2 != null && req.toIso2 !== "") params.set("toIso2", String(req.toIso2));
    if (req.cargoType != null && req.cargoType !== "") params.set("cargoType", String(req.cargoType));
    if (req.hs2 != null && req.hs2 !== "") params.set("hs2", String(req.hs2));
    const url = this.baseURL + path + (params.toString() ? "?" + params.toString() : "");

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...this.defaultHeaders,
      ...options?.headers,
    };

    const resp = await this.fetchFn(url, {
      method: "GET",
      headers,
      signal: options?.signal,
    });

    if (!resp.ok) {
      return this.handleError(resp);
    }

    return await resp.json() as RouteIntelligenceResponse;
  }

  async registerWebhook(req: RegisterWebhookRequest, options?: ShippingV2ServiceCallOptions): Promise<RegisterWebhookResponse> {
    let path = "/api/v2/shipping/webhooks";
    const url = this.baseURL + path;

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...this.defaultHeaders,
      ...options?.headers,
    };

    const resp = await this.fetchFn(url, {
      method: "POST",
      headers,
      body: JSON.stringify(req),
      signal: options?.signal,
    });

    if (!resp.ok) {
      return this.handleError(resp);
    }

    return await resp.json() as RegisterWebhookResponse;
  }

  async listWebhooks(_req: ListWebhooksRequest, options?: ShippingV2ServiceCallOptions): Promise<ListWebhooksResponse> {
    let path = "/api/v2/shipping/webhooks";
    const url = this.baseURL + path;

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...this.defaultHeaders,
      ...options?.headers,
    };

    const resp = await this.fetchFn(url, {
      method: "GET",
      headers,
      signal: options?.signal,
    });

    if (!resp.ok) {
      return this.handleError(resp);
    }

    return await resp.json() as ListWebhooksResponse;
  }

  private async handleError(resp: Response): Promise<never> {
    const body = await resp.text();
    if (resp.status === 400) {
      try {
        const parsed = JSON.parse(body);
        if (parsed.violations) {
          throw new ValidationError(parsed.violations);
        }
      } catch (e) {
        if (e instanceof ValidationError) throw e;
      }
    }
    throw new ApiError(resp.status, `Request failed with status ${resp.status}`, body);
  }
}

