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

export interface RunScenarioRequest {
  scenarioId: string;
  iso2: string;
}

export interface RunScenarioResponse {
  jobId: string;
  status: string;
  statusUrl: string;
}

export interface GetScenarioStatusRequest {
  jobId: string;
}

export interface GetScenarioStatusResponse {
  status: string;
  result?: ScenarioResult;
  error: string;
}

export interface ScenarioResult {
  affectedChokepointIds: string[];
  topImpactCountries: ScenarioImpactCountry[];
  template?: ScenarioResultTemplate;
}

export interface ScenarioImpactCountry {
  iso2: string;
  totalImpact: number;
  impactPct: number;
}

export interface ScenarioResultTemplate {
  name: string;
  disruptionPct: number;
  durationDays: number;
  costShockMultiplier: number;
}

export interface ListScenarioTemplatesRequest {
}

export interface ListScenarioTemplatesResponse {
  templates: ScenarioTemplate[];
}

export interface ScenarioTemplate {
  id: string;
  name: string;
  affectedChokepointIds: string[];
  disruptionPct: number;
  durationDays: number;
  affectedHs2: string[];
  costShockMultiplier: 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 ScenarioServiceHandler {
  runScenario(ctx: ServerContext, req: RunScenarioRequest): Promise<RunScenarioResponse>;
  getScenarioStatus(ctx: ServerContext, req: GetScenarioStatusRequest): Promise<GetScenarioStatusResponse>;
  listScenarioTemplates(ctx: ServerContext, req: ListScenarioTemplatesRequest): Promise<ListScenarioTemplatesResponse>;
}

export function createScenarioServiceRoutes(
  handler: ScenarioServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "POST",
      path: "/api/scenario/v1/run-scenario",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = await req.json() as RunScenarioRequest;
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("runScenario", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.runScenario(ctx, body);
          return new Response(JSON.stringify(result as RunScenarioResponse), {
            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/scenario/v1/get-scenario-status",
      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: GetScenarioStatusRequest = {
            jobId: params.get("jobId") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getScenarioStatus", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getScenarioStatus(ctx, body);
          return new Response(JSON.stringify(result as GetScenarioStatusResponse), {
            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/scenario/v1/list-scenario-templates",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as ListScenarioTemplatesRequest;

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

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

