const mongoose = require('mongoose')

class Database {
  constructor() {
    this.mongoose = mongoose
    this.isConnected = false
  }

  async connect() {
    if (this.isConnected) {
      return
    }

    try {
      // 连接数据库
      const mongodbUri = process.env.MONGODB_URI || 'mongodb://mongodb.jiebanke.com:27017/jiebanke'
      await this.mongoose.connect(mongodbUri, {
        useNewUrlParser: true,
        useUnifiedTopology: true
      })
      
      this.isConnected = true
      console.log('✅ MongoDB连接成功')
      
      // 监听连接事件
      this.mongoose.connection.on('error', (error) => {
        console.error('❌ MongoDB连接错误:', error)
        this.isConnected = false
      })

      this.mongoose.connection.on('disconnected', () => {
        console.warn('⚠️ MongoDB连接断开')
        this.isConnected = false
      })

      this.mongoose.connection.on('reconnected', () => {
        console.log('🔁 MongoDB重新连接成功')
        this.isConnected = true
      })

    } catch (error) {
      console.error('❌ MongoDB连接失败:', error)
      process.exit(1)
    }
  }

  async disconnect() {
    if (!this.isConnected) {
      return
    }

    try {
      await this.mongoose.disconnect()
      this.isConnected = false
      console.log('✅ MongoDB连接已关闭')
    } catch (error) {
      console.error('❌ MongoDB断开连接失败:', error)
    }
  }

  // 健康检查
  async healthCheck() {
    try {
      await this.mongoose.connection.db.admin().ping()
      return { status: 'healthy', connected: this.isConnected }
    } catch (error) {
      return { status: 'unhealthy', connected: this.isConnected, error: error.message }
    }
  }

  // 获取连接状态
  getStatus() {
    return {
      connected: this.isConnected,
      readyState: this.mongoose.connection.readyState,
      host: this.mongoose.connection.host,
      name: this.mongoose.connection.name
    }
  }
}

// 创建单例实例
const database = new Database()

// 进程退出时关闭数据库连接
process.on('SIGINT', async () => {
  await database.disconnect()
  process.exit(0)
})

process.on('SIGTERM', async () => {
  await database.disconnect()
  process.exit(0)
})

module.exports = database