/**
 * @fileoverview Shared types for the Aurora API routing system.
 * Provides type definitions for route handlers, responses, and errors.
 */

/**
 * Standard API error response structure.
 */
export interface ApiErrorResponse {
    error: string;
    details?: string;
    issues?: Array<{ path: (string | number)[]; message: string }>;
}

/**
 * Standard API success response with optional data wrapper.
 */
export interface ApiSuccessResponse<T = unknown> {
    success: true;
    [key: string]: T | true;
}

/**
 * Route context passed to all route handlers.
 * Contains parsed URL information and the original request.
 */
export interface RouteContext {
    /** The original HTTP request */
    req: Request;
    /** Parsed URL object */
    url: URL;
    /** HTTP method (GET, POST, PUT, DELETE, etc.) */
    method: string;
    /** URL pathname without query string */
    pathname: string;
}

/**
 * A route handler function that processes a request and returns a response.
 * Returns null if the route doesn't match, allowing the next handler to try.
 */
export type RouteHandler = (ctx: RouteContext) => Promise<Response | null> | Response | null;

/**
 * A route module that exports a handler function.
 */
export interface RouteModule {
    /** Human-readable name for debugging */
    name: string;
    /** The route handler function */
    handler: RouteHandler;
}

/**
 * Custom API error class with HTTP status code support.
 */
export class ApiError extends Error {
    constructor(
        message: string,
        public readonly status: number = 500,
        public readonly details?: string
    ) {
        super(message);
        this.name = 'ApiError';
    }

    /**
     * Creates a 400 Bad Request error.
     */
    static badRequest(message: string, details?: string): ApiError {
        return new ApiError(message, 400, details);
    }

    /**
     * Creates a 404 Not Found error.
     */
    static notFound(resource: string): ApiError {
        return new ApiError(`${resource} not found`, 404);
    }

    /**
     * Creates a 409 Conflict error.
     */
    static conflict(message: string): ApiError {
        return new ApiError(message, 409);
    }

    /**
     * Creates a 500 Internal Server Error.
     */
    static internal(message: string, details?: string): ApiError {
        return new ApiError(message, 500, details);
    }
}
