import type { NestedRoutes, RouteDefinition } from "./define-module"

/**
 * Route resolution utilities
 */
export class RouteResolver {
  /**
   * Resolve path by combining prefix and route path
   */
  static resolvePath(prefix = "", path: string): string {
    // Remove trailing slashes from prefix
    const cleanPrefix = prefix.replace(/\/+$/, "")
    // Remove leading slashes from path
    const cleanPath = path.replace(/^\/+/, "")

    if (!cleanPath) {
      return cleanPrefix || "/"
    }

    return cleanPrefix ? `${cleanPrefix}/${cleanPath}` : `/${cleanPath}`
  }

  /**
   * Flatten nested routes into a flat structure for proxy consumption
   */
  static flattenRoutes(
    routes: NestedRoutes,
    prefix = "",
    parentKey = "",
  ): Record<string, RouteDefinition> {
    const flattened: Record<string, RouteDefinition> = {}

    for (const [key, value] of Object.entries(routes)) {
      const routeKey = parentKey ? `${parentKey}.${key}` : key

      if (this.isRouteDefinition(value)) {
        // This is a route definition, resolve the full path
        flattened[routeKey] = {
          ...value,
          path: this.resolvePath(prefix, value.path),
        }
      } else {
        // This is a nested route group, recurse
        const nestedFlattened = this.flattenRoutes(
          value as NestedRoutes,
          prefix,
          routeKey,
        )
        Object.assign(flattened, nestedFlattened)
      }
    }

    return flattened
  }

  /**
   * Type guard to check if a value is a RouteDefinition
   */
  private static isRouteDefinition(value: any): value is RouteDefinition {
    return (
      value && typeof value === "object" && "method" in value && "path" in value
    )
  }
}
