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

export interface GetGivingSummaryRequest {
  platformLimit: number;
  categoryLimit: number;
}

export interface GetGivingSummaryResponse {
  summary?: GivingSummary;
}

export interface GivingSummary {
  generatedAt: string;
  activityIndex: number;
  trend: string;
  estimatedDailyFlowUsd: number;
  platforms: PlatformGiving[];
  categories: CategoryBreakdown[];
  crypto?: CryptoGivingSummary;
  institutional?: InstitutionalGiving;
}

export interface PlatformGiving {
  platform: string;
  dailyVolumeUsd: number;
  activeCampaignsSampled: number;
  newCampaigns24h: number;
  donationVelocity: number;
  dataFreshness: string;
  lastUpdated: string;
}

export interface CategoryBreakdown {
  category: string;
  share: number;
  change24h: number;
  activeCampaigns: number;
  trending: boolean;
}

export interface CryptoGivingSummary {
  dailyInflowUsd: number;
  trackedWallets: number;
  transactions24h: number;
  topReceivers: string[];
  pctOfTotal: number;
}

export interface InstitutionalGiving {
  oecdOdaAnnualUsdBn: number;
  oecdDataYear: number;
  cafWorldGivingIndex: number;
  cafDataYear: number;
  candidGrantsTracked: number;
  dataLag: string;
}

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 GivingServiceHandler {
  getGivingSummary(ctx: ServerContext, req: GetGivingSummaryRequest): Promise<GetGivingSummaryResponse>;
}

export function createGivingServiceRoutes(
  handler: GivingServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/giving/v1/get-giving-summary",
      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: GetGivingSummaryRequest = {
            platformLimit: Number(params.get("platform_limit") ?? "0"),
            categoryLimit: Number(params.get("category_limit") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getGivingSummary", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

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

