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

export interface GetTradeRestrictionsRequest {
  countries: string[];
  limit: number;
}

export interface GetTradeRestrictionsResponse {
  restrictions: TradeRestriction[];
  fetchedAt: string;
  upstreamUnavailable: boolean;
}

export interface TradeRestriction {
  id: string;
  reportingCountry: string;
  affectedCountry: string;
  productSector: string;
  measureType: string;
  description: string;
  status: string;
  notifiedAt: string;
  sourceUrl: string;
}

export interface GetTariffTrendsRequest {
  reportingCountry: string;
  partnerCountry: string;
  productSector: string;
  years: number;
}

export interface GetTariffTrendsResponse {
  datapoints: TariffDataPoint[];
  fetchedAt: string;
  upstreamUnavailable: boolean;
  effectiveTariffRate?: EffectiveTariffRate;
}

export interface TariffDataPoint {
  reportingCountry: string;
  partnerCountry: string;
  productSector: string;
  year: number;
  tariffRate: number;
  boundRate: number;
  indicatorCode: string;
}

export interface EffectiveTariffRate {
  sourceName: string;
  sourceUrl: string;
  observationPeriod: string;
  updatedAt: string;
  tariffRate: number;
}

export interface GetTradeFlowsRequest {
  reportingCountry: string;
  partnerCountry: string;
  years: number;
}

export interface GetTradeFlowsResponse {
  flows: TradeFlowRecord[];
  fetchedAt: string;
  upstreamUnavailable: boolean;
}

export interface TradeFlowRecord {
  reportingCountry: string;
  partnerCountry: string;
  year: number;
  exportValueUsd: number;
  importValueUsd: number;
  yoyExportChange: number;
  yoyImportChange: number;
  productSector: string;
}

export interface GetTradeBarriersRequest {
  countries: string[];
  measureType: string;
  limit: number;
}

export interface GetTradeBarriersResponse {
  barriers: TradeBarrier[];
  fetchedAt: string;
  upstreamUnavailable: boolean;
}

export interface TradeBarrier {
  id: string;
  notifyingCountry: string;
  title: string;
  measureType: string;
  productDescription: string;
  objective: string;
  status: string;
  dateDistributed: string;
  sourceUrl: string;
}

export interface GetCustomsRevenueRequest {
}

export interface GetCustomsRevenueResponse {
  months: CustomsRevenueMonth[];
  fetchedAt: string;
  upstreamUnavailable: boolean;
}

export interface CustomsRevenueMonth {
  recordDate: string;
  fiscalYear: number;
  calendarYear: number;
  calendarMonth: number;
  monthlyAmountBillions: number;
  fytdAmountBillions: number;
}

export interface ListComtradeFlowsRequest {
  reporterCode: string;
  cmdCode: string;
  anomaliesOnly: boolean;
}

export interface ListComtradeFlowsResponse {
  flows: ComtradeFlowRecord[];
  fetchedAt: string;
  upstreamUnavailable: boolean;
}

export interface ComtradeFlowRecord {
  reporterCode: string;
  reporterName: string;
  partnerCode: string;
  partnerName: string;
  cmdCode: string;
  cmdDesc: string;
  year: number;
  tradeValueUsd: number;
  netWeightKg: number;
  yoyChange: number;
  isAnomaly: 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 TradeServiceClientOptions {
  fetch?: typeof fetch;
  defaultHeaders?: Record<string, string>;
}

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

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

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

  async getTradeRestrictions(req: GetTradeRestrictionsRequest, options?: TradeServiceCallOptions): Promise<GetTradeRestrictionsResponse> {
    let path = "/api/trade/v1/get-trade-restrictions";
    const params = new URLSearchParams();
    if (req.countries && req.countries.length > 0) req.countries.forEach(v => params.append("countries", v));
    if (req.limit != null && req.limit !== 0) params.set("limit", String(req.limit));
    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 GetTradeRestrictionsResponse;
  }

  async getTariffTrends(req: GetTariffTrendsRequest, options?: TradeServiceCallOptions): Promise<GetTariffTrendsResponse> {
    let path = "/api/trade/v1/get-tariff-trends";
    const params = new URLSearchParams();
    if (req.reportingCountry != null && req.reportingCountry !== "") params.set("reporting_country", String(req.reportingCountry));
    if (req.partnerCountry != null && req.partnerCountry !== "") params.set("partner_country", String(req.partnerCountry));
    if (req.productSector != null && req.productSector !== "") params.set("product_sector", String(req.productSector));
    if (req.years != null && req.years !== 0) params.set("years", String(req.years));
    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 GetTariffTrendsResponse;
  }

  async getTradeFlows(req: GetTradeFlowsRequest, options?: TradeServiceCallOptions): Promise<GetTradeFlowsResponse> {
    let path = "/api/trade/v1/get-trade-flows";
    const params = new URLSearchParams();
    if (req.reportingCountry != null && req.reportingCountry !== "") params.set("reporting_country", String(req.reportingCountry));
    if (req.partnerCountry != null && req.partnerCountry !== "") params.set("partner_country", String(req.partnerCountry));
    if (req.years != null && req.years !== 0) params.set("years", String(req.years));
    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 GetTradeFlowsResponse;
  }

  async getTradeBarriers(req: GetTradeBarriersRequest, options?: TradeServiceCallOptions): Promise<GetTradeBarriersResponse> {
    let path = "/api/trade/v1/get-trade-barriers";
    const params = new URLSearchParams();
    if (req.countries && req.countries.length > 0) req.countries.forEach(v => params.append("countries", v));
    if (req.measureType != null && req.measureType !== "") params.set("measure_type", String(req.measureType));
    if (req.limit != null && req.limit !== 0) params.set("limit", String(req.limit));
    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 GetTradeBarriersResponse;
  }

  async getCustomsRevenue(_req: GetCustomsRevenueRequest, options?: TradeServiceCallOptions): Promise<GetCustomsRevenueResponse> {
    let path = "/api/trade/v1/get-customs-revenue";
    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 GetCustomsRevenueResponse;
  }

  async listComtradeFlows(req: ListComtradeFlowsRequest, options?: TradeServiceCallOptions): Promise<ListComtradeFlowsResponse> {
    let path = "/api/trade/v1/list-comtrade-flows";
    const params = new URLSearchParams();
    if (req.reporterCode != null && req.reporterCode !== "") params.set("reporter_code", String(req.reporterCode));
    if (req.cmdCode != null && req.cmdCode !== "") params.set("cmd_code", String(req.cmdCode));
    if (req.anomaliesOnly) params.set("anomalies_only", String(req.anomaliesOnly));
    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 ListComtradeFlowsResponse;
  }

  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);
  }
}

