// Express compatibility shim for CF Workers
// Allows existing Express route handlers to work with Hono

export type RouteEntry = { method: string; path: string; handlers: Function[] };

export function Router() {
  const routes: RouteEntry[] = [];
  const middlewares: Function[] = [];

  const router: any = function () {};

  for (const method of ['get', 'post', 'put', 'patch', 'delete']) {
    router[method] = (path: string, ...handlers: Function[]) => {
      routes.push({ method: method.toUpperCase(), path, handlers: [...middlewares, ...handlers] });
      return router;
    };
  }

  router.use = (...args: any[]) => {
    if (typeof args[0] === 'string') {
      // router.use('/path', ...middlewaresOrSubRouter)
      const path = args[0];
      const rest = args.slice(1);

      // Find the sub-router (has _routes) — it's typically the last arg
      const subRouterIdx = rest.findIndex((a: any) => a?._routes);
      if (subRouterIdx >= 0) {
        const subRouter = rest[subRouterIdx];
        // Middlewares are everything before the sub-router
        const pathMiddlewares = rest.slice(0, subRouterIdx).filter((a: any) => typeof a === 'function');

        for (const route of subRouter._routes) {
          routes.push({
            method: route.method,
            path: path + route.path,
            // Chain: parent middlewares -> path-level middlewares -> sub-router middlewares from route
            handlers: [...middlewares, ...pathMiddlewares, ...route.handlers],
          });
        }
      } else {
        // All args are middlewares for this path — treat as path-scoped middleware
        for (const fn of rest) {
          if (typeof fn === 'function') {
            // We store path-scoped middlewares as a special route entry
            // They'll match any method and sub-path
            middlewares.push(fn);
          }
        }
      }
    } else {
      // router.use(middleware1, middleware2, ...)
      for (const fn of args) {
        if (typeof fn === 'function') {
          middlewares.push(fn);
        }
      }
    }
    return router;
  };

  router._routes = routes;
  router._middlewares = middlewares;

  return router;
}

// Express app stub
export function express() {
  return Router();
}

// Static middleware stubs
express.json = (_opts?: any) => (_req: any, _res: any, next: any) => next();
express.urlencoded = (_opts?: any) => (_req: any, _res: any, next: any) => next();
express.static = (_path: string, _opts?: any) => (_req: any, _res: any, next: any) => next();
express.Router = Router;
express.raw = (_opts?: any) => (_req: any, _res: any, next: any) => next();

export default express;
export type { Request, Response, NextFunction, ErrorRequestHandler } from './types';
