// @ts-nocheck
// Code generated by protoc-gen-ts-server. 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 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 TradeServiceHandler {
  getTradeRestrictions(ctx: ServerContext, req: GetTradeRestrictionsRequest): Promise<GetTradeRestrictionsResponse>;
  getTariffTrends(ctx: ServerContext, req: GetTariffTrendsRequest): Promise<GetTariffTrendsResponse>;
  getTradeFlows(ctx: ServerContext, req: GetTradeFlowsRequest): Promise<GetTradeFlowsResponse>;
  getTradeBarriers(ctx: ServerContext, req: GetTradeBarriersRequest): Promise<GetTradeBarriersResponse>;
  getCustomsRevenue(ctx: ServerContext, req: GetCustomsRevenueRequest): Promise<GetCustomsRevenueResponse>;
  listComtradeFlows(ctx: ServerContext, req: ListComtradeFlowsRequest): Promise<ListComtradeFlowsResponse>;
}

export function createTradeServiceRoutes(
  handler: TradeServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/trade/v1/get-trade-restrictions",
      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: GetTradeRestrictionsRequest = {
            countries: params.get("countries") ?? "",
            limit: Number(params.get("limit") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getTradeRestrictions", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getTradeRestrictions(ctx, body);
          return new Response(JSON.stringify(result as GetTradeRestrictionsResponse), {
            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/trade/v1/get-tariff-trends",
      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: GetTariffTrendsRequest = {
            reportingCountry: params.get("reporting_country") ?? "",
            partnerCountry: params.get("partner_country") ?? "",
            productSector: params.get("product_sector") ?? "",
            years: Number(params.get("years") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getTariffTrends", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getTariffTrends(ctx, body);
          return new Response(JSON.stringify(result as GetTariffTrendsResponse), {
            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/trade/v1/get-trade-flows",
      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: GetTradeFlowsRequest = {
            reportingCountry: params.get("reporting_country") ?? "",
            partnerCountry: params.get("partner_country") ?? "",
            years: Number(params.get("years") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getTradeFlows", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getTradeFlows(ctx, body);
          return new Response(JSON.stringify(result as GetTradeFlowsResponse), {
            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/trade/v1/get-trade-barriers",
      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: GetTradeBarriersRequest = {
            countries: params.get("countries") ?? "",
            measureType: params.get("measure_type") ?? "",
            limit: Number(params.get("limit") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getTradeBarriers", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getTradeBarriers(ctx, body);
          return new Response(JSON.stringify(result as GetTradeBarriersResponse), {
            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/trade/v1/get-customs-revenue",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as GetCustomsRevenueRequest;

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

          const result = await handler.getCustomsRevenue(ctx, body);
          return new Response(JSON.stringify(result as GetCustomsRevenueResponse), {
            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/trade/v1/list-comtrade-flows",
      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: ListComtradeFlowsRequest = {
            reporterCode: params.get("reporter_code") ?? "",
            cmdCode: params.get("cmd_code") ?? "",
            anomaliesOnly: params.get("anomalies_only") === "true",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listComtradeFlows", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

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

