import { getTokenFromRequest } from './chunk-OCR5DS4C.mjs';

// src/auth/middleware/with-auth.ts
function createAuthMiddleware(config) {
  function withAuth(handler, level = "user") {
    return async (request, context = {}) => {
      if (level === "none") {
        return await handler(request, context);
      }
      try {
        const token = getTokenFromRequest(request);
        if (!token) {
          return new Response(
            JSON.stringify({
              success: false,
              error: "\u672A\u63D0\u4F9B\u8BA4\u8BC1\u4EE4\u724C"
            }),
            {
              status: 401,
              headers: { "Content-Type": "application/json" }
            }
          );
        }
        const result = await config.authService.verifyToken(token);
        if (level === "admin" || level === "super_admin") {
          if (!["ADMIN", "SUPER_ADMIN"].includes(result.user.role)) {
            return new Response(
              JSON.stringify({
                success: false,
                error: "\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650"
              }),
              {
                status: 403,
                headers: { "Content-Type": "application/json" }
              }
            );
          }
        }
        if (level === "super_admin") {
          if (result.user.role !== "SUPER_ADMIN") {
            return new Response(
              JSON.stringify({
                success: false,
                error: "\u9700\u8981\u8D85\u7EA7\u7BA1\u7406\u5458\u6743\u9650"
              }),
              {
                status: 403,
                headers: { "Content-Type": "application/json" }
              }
            );
          }
        }
        context.user = result.user;
        context.session = result.session;
        return await handler(request, context);
      } catch (error) {
        console.error("Auth middleware error:", error);
        return new Response(
          JSON.stringify({
            success: false,
            error: "\u8BA4\u8BC1\u5931\u8D25"
          }),
          {
            status: 401,
            headers: { "Content-Type": "application/json" }
          }
        );
      }
    };
  }
  function requireAuth(handler) {
    return withAuth(handler, "user");
  }
  function requireAdmin(handler) {
    return withAuth(handler, "admin");
  }
  function requireSuperAdmin(handler) {
    return withAuth(handler, "super_admin");
  }
  return {
    withAuth,
    requireAuth,
    requireAdmin,
    requireSuperAdmin
  };
}

export { createAuthMiddleware };
//# sourceMappingURL=chunk-ESRCX5TQ.mjs.map
//# sourceMappingURL=chunk-ESRCX5TQ.mjs.map