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

export interface GetConsumerPriceOverviewRequest {
  marketCode: string;
  basketSlug: string;
}

export interface GetConsumerPriceOverviewResponse {
  marketCode: string;
  asOf: string;
  currencyCode: string;
  essentialsIndex: number;
  valueBasketIndex: number;
  wowPct: number;
  momPct: number;
  retailerSpreadPct: number;
  coveragePct: number;
  freshnessLagMin: number;
  topCategories: CategorySnapshot[];
  upstreamUnavailable: boolean;
}

export interface CategorySnapshot {
  slug: string;
  name: string;
  wowPct: number;
  momPct: number;
  currentIndex: number;
  sparkline: number[];
  coveragePct: number;
  itemCount: number;
}

export interface GetConsumerPriceBasketSeriesRequest {
  marketCode: string;
  basketSlug: string;
  range: string;
}

export interface GetConsumerPriceBasketSeriesResponse {
  marketCode: string;
  basketSlug: string;
  asOf: string;
  currencyCode: string;
  range: string;
  essentialsSeries: BasketPoint[];
  valueSeries: BasketPoint[];
  upstreamUnavailable: boolean;
}

export interface BasketPoint {
  date: string;
  index: number;
}

export interface ListConsumerPriceCategoriesRequest {
  marketCode: string;
  basketSlug: string;
  range: string;
}

export interface ListConsumerPriceCategoriesResponse {
  marketCode: string;
  asOf: string;
  range: string;
  categories: CategorySnapshot[];
  upstreamUnavailable: boolean;
}

export interface ListConsumerPriceMoversRequest {
  marketCode: string;
  range: string;
  limit: number;
  categorySlug: string;
}

export interface ListConsumerPriceMoversResponse {
  marketCode: string;
  asOf: string;
  range: string;
  risers: PriceMover[];
  fallers: PriceMover[];
  upstreamUnavailable: boolean;
}

export interface PriceMover {
  productId: string;
  title: string;
  category: string;
  retailerSlug: string;
  changePct: number;
  currentPrice: number;
  currencyCode: string;
}

export interface ListRetailerPriceSpreadsRequest {
  marketCode: string;
  basketSlug: string;
}

export interface ListRetailerPriceSpreadsResponse {
  marketCode: string;
  asOf: string;
  basketSlug: string;
  currencyCode: string;
  retailers: RetailerSpread[];
  spreadPct: number;
  upstreamUnavailable: boolean;
}

export interface RetailerSpread {
  slug: string;
  name: string;
  basketTotal: number;
  deltaVsCheapest: number;
  deltaVsCheapestPct: number;
  itemCount: number;
  freshnessMin: number;
  currencyCode: string;
}

export interface GetConsumerPriceFreshnessRequest {
  marketCode: string;
}

export interface GetConsumerPriceFreshnessResponse {
  marketCode: string;
  asOf: string;
  retailers: RetailerFreshnessInfo[];
  overallFreshnessMin: number;
  stalledCount: number;
  upstreamUnavailable: boolean;
}

export interface RetailerFreshnessInfo {
  slug: string;
  name: string;
  lastRunAt: string;
  status: string;
  parseSuccessRate: number;
  freshnessMin: number;
}

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 ConsumerPricesServiceHandler {
  getConsumerPriceOverview(ctx: ServerContext, req: GetConsumerPriceOverviewRequest): Promise<GetConsumerPriceOverviewResponse>;
  getConsumerPriceBasketSeries(ctx: ServerContext, req: GetConsumerPriceBasketSeriesRequest): Promise<GetConsumerPriceBasketSeriesResponse>;
  listConsumerPriceCategories(ctx: ServerContext, req: ListConsumerPriceCategoriesRequest): Promise<ListConsumerPriceCategoriesResponse>;
  listConsumerPriceMovers(ctx: ServerContext, req: ListConsumerPriceMoversRequest): Promise<ListConsumerPriceMoversResponse>;
  listRetailerPriceSpreads(ctx: ServerContext, req: ListRetailerPriceSpreadsRequest): Promise<ListRetailerPriceSpreadsResponse>;
  getConsumerPriceFreshness(ctx: ServerContext, req: GetConsumerPriceFreshnessRequest): Promise<GetConsumerPriceFreshnessResponse>;
}

export function createConsumerPricesServiceRoutes(
  handler: ConsumerPricesServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/consumer-prices/v1/get-consumer-price-overview",
      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: GetConsumerPriceOverviewRequest = {
            marketCode: params.get("market_code") ?? "",
            basketSlug: params.get("basket_slug") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getConsumerPriceOverview", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getConsumerPriceOverview(ctx, body);
          return new Response(JSON.stringify(result as GetConsumerPriceOverviewResponse), {
            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/consumer-prices/v1/get-consumer-price-basket-series",
      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: GetConsumerPriceBasketSeriesRequest = {
            marketCode: params.get("market_code") ?? "",
            basketSlug: params.get("basket_slug") ?? "",
            range: params.get("range") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getConsumerPriceBasketSeries", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getConsumerPriceBasketSeries(ctx, body);
          return new Response(JSON.stringify(result as GetConsumerPriceBasketSeriesResponse), {
            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/consumer-prices/v1/list-consumer-price-categories",
      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: ListConsumerPriceCategoriesRequest = {
            marketCode: params.get("market_code") ?? "",
            basketSlug: params.get("basket_slug") ?? "",
            range: params.get("range") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listConsumerPriceCategories", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.listConsumerPriceCategories(ctx, body);
          return new Response(JSON.stringify(result as ListConsumerPriceCategoriesResponse), {
            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/consumer-prices/v1/list-consumer-price-movers",
      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: ListConsumerPriceMoversRequest = {
            marketCode: params.get("market_code") ?? "",
            range: params.get("range") ?? "",
            limit: Number(params.get("limit") ?? "0"),
            categorySlug: params.get("category_slug") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listConsumerPriceMovers", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.listConsumerPriceMovers(ctx, body);
          return new Response(JSON.stringify(result as ListConsumerPriceMoversResponse), {
            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/consumer-prices/v1/list-retailer-price-spreads",
      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: ListRetailerPriceSpreadsRequest = {
            marketCode: params.get("market_code") ?? "",
            basketSlug: params.get("basket_slug") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listRetailerPriceSpreads", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.listRetailerPriceSpreads(ctx, body);
          return new Response(JSON.stringify(result as ListRetailerPriceSpreadsResponse), {
            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/consumer-prices/v1/get-consumer-price-freshness",
      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: GetConsumerPriceFreshnessRequest = {
            marketCode: params.get("market_code") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getConsumerPriceFreshness", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

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

