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

// src/auth/routes/login.ts
function addCorsHeaders(response, config, request) {
  if (!config.cors?.enabled) return response;
  const origin = request.headers.get("origin");
  const allowedOrigins = config.cors.origin;
  if (allowedOrigins) {
    if (typeof allowedOrigins === "string") {
      response.headers.set("Access-Control-Allow-Origin", allowedOrigins);
    } else if (Array.isArray(allowedOrigins) && origin && allowedOrigins.includes(origin)) {
      response.headers.set("Access-Control-Allow-Origin", origin);
    }
  } else {
    response.headers.set("Access-Control-Allow-Origin", origin || "*");
  }
  if (config.cors.credentials) {
    response.headers.set("Access-Control-Allow-Credentials", "true");
  }
  const methods = config.cors.methods || ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
  response.headers.set("Access-Control-Allow-Methods", methods.join(", "));
  const headers = config.cors.allowedHeaders || ["Content-Type", "Authorization"];
  response.headers.set("Access-Control-Allow-Headers", headers.join(", "));
  return response;
}
function createLoginHandler(config) {
  return async (request) => {
    let requestBody = {};
    try {
      requestBody = await request.json();
      const { email, password } = requestBody;
      if (!email || !password) {
        const response2 = new Response(
          JSON.stringify({
            success: false,
            error: "\u90AE\u7BB1\u548C\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A"
          }),
          {
            status: 400,
            headers: { "Content-Type": "application/json" }
          }
        );
        return addCorsHeaders(response2, config, request);
      }
      const result = await config.authService.signIn(email, password);
      if (config.analytics) {
        try {
          await config.analytics.track("user_login_success", {
            userId: result.user.id,
            userRole: result.user.role,
            email: result.user.email,
            loginMethod: "email_password",
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        } catch (analyticsError) {
          console.error("Failed to track login analytics:", analyticsError);
        }
      }
      const response = new Response(
        JSON.stringify({
          success: true,
          data: {
            user: result.user,
            token: result.token
          },
          message: "\u767B\u5F55\u6210\u529F"
        }),
        {
          status: 200,
          headers: { "Content-Type": "application/json" }
        }
      );
      if (config.cookieOptions) {
        const cookieOptions = {
          name: config.cookieOptions?.name || "auth_token",
          httpOnly: config.cookieOptions?.httpOnly !== false,
          secure: config.cookieOptions?.secure !== false && process.env.NODE_ENV === "production",
          sameSite: config.cookieOptions?.sameSite || "lax",
          maxAge: config.cookieOptions?.maxAge || 60 * 60 * 24 * 7,
          // 7天
          path: config.cookieOptions?.path || "/"
        };
        const cookieValue = `${cookieOptions.name}=${result.token}; HttpOnly=${cookieOptions.httpOnly}; Secure=${cookieOptions.secure}; SameSite=${cookieOptions.sameSite}; Max-Age=${cookieOptions.maxAge}; Path=${cookieOptions.path}`;
        response.headers.set("Set-Cookie", cookieValue);
      }
      return addCorsHeaders(response, config, request);
    } catch (error) {
      console.error("Login error:", error);
      if (config.analytics) {
        try {
          await config.analytics.track("user_login_failed", {
            errorMessage: error.message || "\u767B\u5F55\u5931\u8D25",
            email: requestBody.email,
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        } catch (analyticsError) {
          console.error("Failed to track login failure analytics:", analyticsError);
        }
      }
      const response = new Response(
        JSON.stringify({
          success: false,
          error: error.message || "\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u90AE\u7BB1\u548C\u5BC6\u7801"
        }),
        {
          status: 401,
          headers: { "Content-Type": "application/json" }
        }
      );
      return addCorsHeaders(response, config, request);
    }
  };
}
function createLoginOptionsHandler(config) {
  return async (request) => {
    const response = new Response(null, {
      status: 204,
      headers: {
        "Content-Length": "0"
      }
    });
    return addCorsHeaders(response, config, request);
  };
}

// src/auth/routes/register.ts
function addCorsHeaders2(response, config, request) {
  if (!config.cors?.enabled) return response;
  const origin = request.headers.get("origin");
  const allowedOrigins = config.cors.origin;
  if (allowedOrigins) {
    if (typeof allowedOrigins === "string") {
      response.headers.set("Access-Control-Allow-Origin", allowedOrigins);
    } else if (Array.isArray(allowedOrigins) && origin && allowedOrigins.includes(origin)) {
      response.headers.set("Access-Control-Allow-Origin", origin);
    }
  } else {
    response.headers.set("Access-Control-Allow-Origin", origin || "*");
  }
  if (config.cors.credentials) {
    response.headers.set("Access-Control-Allow-Credentials", "true");
  }
  const methods = config.cors.methods || ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
  response.headers.set("Access-Control-Allow-Methods", methods.join(", "));
  const headers = config.cors.allowedHeaders || ["Content-Type", "Authorization"];
  response.headers.set("Access-Control-Allow-Headers", headers.join(", "));
  return response;
}
function createRegisterHandler(config) {
  return async (request) => {
    try {
      const { email, password, username } = await request.json();
      if (!email || !password) {
        const response2 = new Response(
          JSON.stringify({
            success: false,
            error: "\u90AE\u7BB1\u548C\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A"
          }),
          {
            status: 400,
            headers: { "Content-Type": "application/json" }
          }
        );
        return addCorsHeaders2(response2, config, request);
      }
      if (password.length < 6) {
        const response2 = new Response(
          JSON.stringify({
            success: false,
            error: "\u5BC6\u7801\u957F\u5EA6\u81F3\u5C11\u4E3A 6 \u4F4D"
          }),
          {
            status: 400,
            headers: { "Content-Type": "application/json" }
          }
        );
        return addCorsHeaders2(response2, config, request);
      }
      const result = await config.authService.signUp(
        email,
        password,
        username,
        config.defaultRole || "USER"
      );
      if (config.analytics) {
        try {
          await config.analytics.track("user_register_success", {
            userId: result.user.id,
            email: result.user.email,
            username: result.user.username,
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        } catch (analyticsError) {
          console.error("Failed to track register analytics:", analyticsError);
        }
      }
      const response = new Response(
        JSON.stringify({
          success: true,
          data: {
            user: result.user,
            token: result.token
          },
          message: "\u6CE8\u518C\u6210\u529F"
        }),
        {
          status: 201,
          headers: { "Content-Type": "application/json" }
        }
      );
      if (config.cookieOptions) {
        const cookieOptions = {
          name: config.cookieOptions?.name || "auth_token",
          httpOnly: config.cookieOptions?.httpOnly !== false,
          secure: config.cookieOptions?.secure !== false && process.env.NODE_ENV === "production",
          sameSite: config.cookieOptions?.sameSite || "lax",
          maxAge: config.cookieOptions?.maxAge || 60 * 60 * 24 * 7,
          path: config.cookieOptions?.path || "/"
        };
        const cookieValue = `${cookieOptions.name}=${result.token}; HttpOnly=${cookieOptions.httpOnly}; Secure=${cookieOptions.secure}; SameSite=${cookieOptions.sameSite}; Max-Age=${cookieOptions.maxAge}; Path=${cookieOptions.path}`;
        response.headers.set("Set-Cookie", cookieValue);
      }
      return addCorsHeaders2(response, config, request);
    } catch (error) {
      console.error("Register error:", error);
      if (config.analytics) {
        try {
          await config.analytics.track("user_register_failed", {
            errorMessage: error.message || "\u6CE8\u518C\u5931\u8D25",
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        } catch (analyticsError) {
          console.error("Failed to track register failure analytics:", analyticsError);
        }
      }
      const response = new Response(
        JSON.stringify({
          success: false,
          error: error.message || "\u6CE8\u518C\u5931\u8D25"
        }),
        {
          status: 400,
          headers: { "Content-Type": "application/json" }
        }
      );
      return addCorsHeaders2(response, config, request);
    }
  };
}
function createRegisterOptionsHandler(config) {
  return async (request) => {
    const response = new Response(null, {
      status: 204,
      headers: {
        "Content-Length": "0"
      }
    });
    if (config.cors?.enabled) {
      const origin = request.headers.get("origin");
      const allowedOrigins = config.cors.origin;
      if (allowedOrigins) {
        if (typeof allowedOrigins === "string") {
          response.headers.set("Access-Control-Allow-Origin", allowedOrigins);
        } else if (Array.isArray(allowedOrigins) && origin && allowedOrigins.includes(origin)) {
          response.headers.set("Access-Control-Allow-Origin", origin);
        }
      } else {
        response.headers.set("Access-Control-Allow-Origin", origin || "*");
      }
      if (config.cors.credentials) {
        response.headers.set("Access-Control-Allow-Credentials", "true");
      }
      const methods = config.cors.methods || ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
      response.headers.set("Access-Control-Allow-Methods", methods.join(", "));
      const headers = config.cors.allowedHeaders || ["Content-Type", "Authorization"];
      response.headers.set("Access-Control-Allow-Headers", headers.join(", "));
    }
    return response;
  };
}

// src/auth/routes/me.ts
function addCorsHeaders3(response, config, request) {
  if (!config.cors?.enabled) return response;
  const origin = request.headers.get("origin");
  const allowedOrigins = config.cors.origin;
  if (allowedOrigins) {
    if (typeof allowedOrigins === "string") {
      response.headers.set("Access-Control-Allow-Origin", allowedOrigins);
    } else if (Array.isArray(allowedOrigins) && origin && allowedOrigins.includes(origin)) {
      response.headers.set("Access-Control-Allow-Origin", origin);
    }
  } else {
    response.headers.set("Access-Control-Allow-Origin", origin || "*");
  }
  if (config.cors.credentials) {
    response.headers.set("Access-Control-Allow-Credentials", "true");
  }
  const methods = config.cors.methods || ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
  response.headers.set("Access-Control-Allow-Methods", methods.join(", "));
  const headers = config.cors.allowedHeaders || ["Content-Type", "Authorization"];
  response.headers.set("Access-Control-Allow-Headers", headers.join(", "));
  return response;
}
function createMeHandler(config) {
  return async (request) => {
    try {
      const token = getTokenFromRequest(request);
      if (!token) {
        const response2 = new Response(
          JSON.stringify({
            success: false,
            error: "\u672A\u63D0\u4F9B\u8BA4\u8BC1\u4EE4\u724C"
          }),
          {
            status: 401,
            headers: { "Content-Type": "application/json" }
          }
        );
        return addCorsHeaders3(response2, config, request);
      }
      const result = await config.authService.verifyToken(token);
      const response = new Response(
        JSON.stringify({
          success: true,
          data: result.user
        }),
        {
          status: 200,
          headers: { "Content-Type": "application/json" }
        }
      );
      return addCorsHeaders3(response, config, request);
    } catch (error) {
      console.error("Get user info error:", error);
      const response = new Response(
        JSON.stringify({
          success: false,
          error: "\u8BA4\u8BC1\u5931\u8D25"
        }),
        {
          status: 401,
          headers: { "Content-Type": "application/json" }
        }
      );
      return addCorsHeaders3(response, config, request);
    }
  };
}
function createMeOptionsHandler(config) {
  return async (request) => {
    const response = new Response(null, {
      status: 204,
      headers: {
        "Content-Length": "0"
      }
    });
    return addCorsHeaders3(response, config, request);
  };
}

// src/auth/routes/logout.ts
function addCorsHeaders4(response, config, request) {
  if (!config.cors?.enabled) return response;
  const origin = request.headers.get("origin");
  const allowedOrigins = config.cors.origin;
  if (allowedOrigins) {
    if (typeof allowedOrigins === "string") {
      response.headers.set("Access-Control-Allow-Origin", allowedOrigins);
    } else if (Array.isArray(allowedOrigins) && origin && allowedOrigins.includes(origin)) {
      response.headers.set("Access-Control-Allow-Origin", origin);
    }
  } else {
    response.headers.set("Access-Control-Allow-Origin", origin || "*");
  }
  if (config.cors.credentials) {
    response.headers.set("Access-Control-Allow-Credentials", "true");
  }
  const methods = config.cors.methods || ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
  response.headers.set("Access-Control-Allow-Methods", methods.join(", "));
  const headers = config.cors.allowedHeaders || ["Content-Type", "Authorization"];
  response.headers.set("Access-Control-Allow-Headers", headers.join(", "));
  return response;
}
function createLogoutHandler(config) {
  return async (request) => {
    try {
      const token = getTokenFromRequest(request);
      if (!token) {
        const response2 = new Response(
          JSON.stringify({
            success: false,
            error: "\u672A\u63D0\u4F9B\u8BA4\u8BC1\u4EE4\u724C"
          }),
          {
            status: 401,
            headers: { "Content-Type": "application/json" }
          }
        );
        return addCorsHeaders4(response2, config, request);
      }
      await config.authService.signOut(token);
      if (config.analytics) {
        try {
          await config.analytics.track("user_logout", {
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        } catch (analyticsError) {
          console.error("Failed to track logout analytics:", analyticsError);
        }
      }
      const response = new Response(
        JSON.stringify({
          success: true,
          message: "\u767B\u51FA\u6210\u529F"
        }),
        {
          status: 200,
          headers: { "Content-Type": "application/json" }
        }
      );
      response.headers.set(
        "Set-Cookie",
        "auth_token=; HttpOnly; Secure; SameSite=Lax; Max-Age=0; Path=/"
      );
      return addCorsHeaders4(response, config, request);
    } catch (error) {
      console.error("Logout error:", error);
      const response = new Response(
        JSON.stringify({
          success: false,
          error: "\u767B\u51FA\u5931\u8D25"
        }),
        {
          status: 500,
          headers: { "Content-Type": "application/json" }
        }
      );
      return addCorsHeaders4(response, config, request);
    }
  };
}
function createLogoutOptionsHandler(config) {
  return async (request) => {
    const response = new Response(null, {
      status: 204,
      headers: {
        "Content-Length": "0"
      }
    });
    return addCorsHeaders4(response, config, request);
  };
}

// src/auth/routes/defaults.ts
function createDefaultBaseConfig(authService, overrides) {
  return {
    authService,
    cors: {
      enabled: true,
      credentials: true,
      ...overrides?.cors
    },
    analytics: overrides?.analytics
  };
}
function createDefaultLoginConfig(authService, overrides) {
  return {
    authService,
    cors: {
      enabled: true,
      credentials: true,
      ...overrides?.cors
    },
    cookieOptions: {
      name: "auth_token",
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 60 * 24 * 7,
      // 7天
      path: "/",
      ...overrides?.cookieOptions
    },
    analytics: overrides?.analytics
  };
}
function createDefaultRegisterConfig(authService, overrides) {
  return {
    authService,
    defaultRole: overrides?.defaultRole || "USER",
    cors: {
      enabled: true,
      credentials: true,
      ...overrides?.cors
    },
    cookieOptions: overrides?.cookieOptions !== void 0 ? {
      name: "auth_token",
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 60 * 24 * 7,
      // 7天
      path: "/",
      ...overrides.cookieOptions
    } : void 0,
    analytics: overrides?.analytics,
    emailVerificationRequired: overrides?.emailVerificationRequired
  };
}

// src/auth/routes/analytics-adapter.ts
function createAnalyticsAdapter(analyticsService, options) {
  const config = {
    platform: options?.platform || "backend",
    appVersion: options?.appVersion || "1.0.0",
    sdkVersion: options?.sdkVersion || "1.0.0",
    deviceId: options?.deviceId || "server",
    generateId: options?.generateId || (() => {
      return `${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
    })
  };
  return {
    track: async (eventName, properties) => {
      try {
        let eventType = "event";
        if (eventName.includes("login_success")) {
          eventType = "login";
        } else if (eventName.includes("register_success")) {
          eventType = "register";
        } else if (eventName.includes("logout")) {
          eventType = "logout";
        } else if (eventName.includes("failed") || eventName.includes("error")) {
          eventType = "error";
        }
        const event = {
          id: config.generateId(),
          eventType,
          eventName,
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          priority: 1,
          userId: properties.userId || "anonymous",
          sessionId: properties.sessionId || `session_${Date.now()}_${properties.userId || "anonymous"}`,
          deviceId: config.deviceId,
          platform: config.platform,
          appVersion: config.appVersion,
          sdkVersion: config.sdkVersion,
          properties
        };
        await analyticsService.insertAnalyticsEvents([event]);
      } catch (error) {
        console.error("Failed to track analytics:", error);
      }
    }
  };
}

export { createAnalyticsAdapter, createDefaultBaseConfig, createDefaultLoginConfig, createDefaultRegisterConfig, createLoginHandler, createLoginOptionsHandler, createLogoutHandler, createLogoutOptionsHandler, createMeHandler, createMeOptionsHandler, createRegisterHandler, createRegisterOptionsHandler };
//# sourceMappingURL=chunk-QAT2RWAO.mjs.map
//# sourceMappingURL=chunk-QAT2RWAO.mjs.map