import { user, session } from './chunk-AIKEVVDR.mjs';
import { eq, and, gt } from 'drizzle-orm';
import { randomBytes } from 'crypto';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';

async function hashPassword(password, saltRounds = 12) {
  return bcrypt.hash(password, saltRounds);
}
async function verifyPassword(password, hashedPassword) {
  return bcrypt.compare(password, hashedPassword);
}
function generateToken(payload, secret, expiresIn = "7d") {
  return jwt.sign(payload, secret, { expiresIn });
}
function verifyJwtToken(token, secret) {
  return jwt.verify(token, secret);
}
function getTokenFromRequest(request) {
  const cookieHeader = request.headers.get("Cookie");
  if (cookieHeader) {
    const match = cookieHeader.match(/auth_token=([^;]+)/);
    if (match && match[1]) {
      return match[1];
    }
  }
  const authHeader = request.headers.get("Authorization");
  if (authHeader && authHeader.startsWith("Bearer ")) {
    const token = authHeader.substring(7);
    return token || null;
  }
  return null;
}

// src/auth/services/drizzle-auth-service.ts
var DrizzleAuthService = class {
  constructor(config) {
    this.config = {
      db: config.db,
      jwtSecret: config.jwtSecret,
      jwtExpiresIn: config.jwtExpiresIn || "7d",
      saltRounds: config.saltRounds || 12,
      checkSecretStrength: config.checkSecretStrength !== false
    };
    this.validateConfig();
  }
  /**
   * 验证配置
   */
  validateConfig() {
    if (!this.config.jwtSecret) {
      throw new Error(
        `JWT_SECRET is required. Please provide jwtSecret in config. You can generate a secure secret with: node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"`
      );
    }
    if (this.config.checkSecretStrength && process.env.NODE_ENV === "production" && this.config.jwtSecret.length < 32) {
      throw new Error(
        "JWT_SECRET is too short (" + this.config.jwtSecret.length + " chars, minimum 32 required in production)"
      );
    }
  }
  /**
   * 用户注册
   */
  async signUp(email, password, username, role = "USER") {
    try {
      const existingUser = await this.config.db.select().from(user).where(eq(user.email, email)).limit(1);
      if (existingUser.length > 0) {
        throw new Error("\u7528\u6237\u5DF2\u5B58\u5728");
      }
      const hashedPassword = await hashPassword(password, this.config.saltRounds);
      const [newUser] = await this.config.db.insert(user).values({
        id: randomBytes(16).toString("hex"),
        email,
        password: hashedPassword,
        username: username || email.split("@")[0],
        role,
        emailVerified: false,
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      }).returning();
      const token = generateToken(
        {
          userId: newUser.id,
          email: newUser.email,
          role: newUser.role
        },
        this.config.jwtSecret,
        this.config.jwtExpiresIn
      );
      await this.createSession(newUser.id, token);
      return {
        user: {
          id: newUser.id,
          email: newUser.email,
          username: newUser.username,
          role: newUser.role
        },
        token
      };
    } catch (error) {
      throw error;
    }
  }
  /**
   * 用户登录
   */
  async signIn(email, password) {
    try {
      const [foundUser] = await this.config.db.select().from(user).where(eq(user.email, email)).limit(1);
      if (!foundUser) {
        throw new Error("\u90AE\u7BB1\u6216\u5BC6\u7801\u9519\u8BEF");
      }
      if (!foundUser.password) {
        throw new Error("\u7528\u6237\u5BC6\u7801\u672A\u8BBE\u7F6E");
      }
      const isPasswordValid = await verifyPassword(password, foundUser.password);
      if (!isPasswordValid) {
        throw new Error("\u90AE\u7BB1\u6216\u5BC6\u7801\u9519\u8BEF");
      }
      const token = generateToken(
        {
          userId: foundUser.id,
          email: foundUser.email,
          role: foundUser.role
        },
        this.config.jwtSecret,
        this.config.jwtExpiresIn
      );
      await this.createSession(foundUser.id, token);
      return {
        user: {
          id: foundUser.id,
          email: foundUser.email,
          username: foundUser.username,
          role: foundUser.role
        },
        token
      };
    } catch (error) {
      throw error;
    }
  }
  /**
   * 验证 Token
   */
  async verifyToken(token) {
    try {
      const decoded = verifyJwtToken(token, this.config.jwtSecret);
      const [foundSession] = await this.config.db.select().from(session).where(
        and(eq(session.token, token), gt(session.expiresAt, (/* @__PURE__ */ new Date()).toISOString()))
      ).limit(1);
      if (!foundSession) {
        throw new Error("\u4F1A\u8BDD\u65E0\u6548\u6216\u5DF2\u8FC7\u671F");
      }
      const [foundUser] = await this.config.db.select().from(user).where(eq(user.id, decoded.userId)).limit(1);
      if (!foundUser) {
        throw new Error("\u7528\u6237\u4E0D\u5B58\u5728");
      }
      return {
        user: {
          id: foundUser.id,
          email: foundUser.email,
          username: foundUser.username,
          role: foundUser.role
        },
        session: foundSession
      };
    } catch (error) {
      throw error;
    }
  }
  /**
   * 创建会话
   */
  async createSession(userId, token, ipAddress, userAgent) {
    const expiresAt = /* @__PURE__ */ new Date();
    expiresAt.setDate(expiresAt.getDate() + 7);
    await this.config.db.insert(session).values({
      id: randomBytes(16).toString("hex"),
      userId,
      token,
      expiresAt: expiresAt.toISOString(),
      ipAddress,
      userAgent,
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    });
  }
  /**
   * 删除会话（登出）
   */
  async signOut(token) {
    try {
      await this.config.db.delete(session).where(eq(session.token, token));
      return { success: true };
    } catch (error) {
      throw error;
    }
  }
  /**
   * 获取会话
   */
  async getSession(token) {
    try {
      return await this.verifyToken(token);
    } catch (error) {
      return null;
    }
  }
  /**
   * 检查管理员权限
   */
  async requireAdmin(token) {
    const result = await this.verifyToken(token);
    if (!["ADMIN", "SUPER_ADMIN"].includes(result.user.role)) {
      throw new Error("\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650");
    }
    return result;
  }
  /**
   * 检查超级管理员权限
   */
  async requireSuperAdmin(token) {
    const result = await this.verifyToken(token);
    if (result.user.role !== "SUPER_ADMIN") {
      throw new Error("\u9700\u8981\u8D85\u7EA7\u7BA1\u7406\u5458\u6743\u9650");
    }
    return result;
  }
  /**
   * 通过用户 ID 获取用户信息
   */
  async getUserById(userId) {
    try {
      const [foundUser] = await this.config.db.select().from(user).where(eq(user.id, userId)).limit(1);
      if (!foundUser) {
        return null;
      }
      return {
        id: foundUser.id,
        email: foundUser.email,
        username: foundUser.username,
        role: foundUser.role
      };
    } catch (error) {
      return null;
    }
  }
  /**
   * 通过邮箱获取用户信息
   */
  async getUserByEmail(email) {
    try {
      const [foundUser] = await this.config.db.select().from(user).where(eq(user.email, email)).limit(1);
      if (!foundUser) {
        return null;
      }
      return {
        id: foundUser.id,
        email: foundUser.email,
        username: foundUser.username,
        role: foundUser.role
      };
    } catch (error) {
      return null;
    }
  }
};

export { DrizzleAuthService, generateToken, getTokenFromRequest, hashPassword, verifyJwtToken, verifyPassword };
//# sourceMappingURL=chunk-PE5EAHZK.mjs.map
//# sourceMappingURL=chunk-PE5EAHZK.mjs.map