/**
 * Alert 模型定义
 * @file Alert.js
 * @description 定义预警模型，用于数据库操作
 */
const { DataTypes } = require('sequelize');
const BaseModel = require('./BaseModel');
const { sequelize } = require('../config/database-simple');

/**
 * 预警模型
 * @typedef {Object} Alert
 * @property {number} id - 预警唯一标识
 * @property {string} type - 预警类型
 * @property {string} level - 预警级别
 * @property {string} message - 预警消息
 * @property {string} status - 预警状态
 * @property {number} farmId - 所属养殖场ID
 * @property {number} deviceId - 关联设备ID
 * @property {Date} created_at - 创建时间
 * @property {Date} updated_at - 更新时间
 */
class Alert extends BaseModel {
  /**
   * 获取预警所属的养殖场
   * @returns {Promise<Object>} 养殖场信息
   */
  async getFarm() {
    return await this.getFarm();
  }

  /**
   * 获取预警关联的设备
   * @returns {Promise<Object>} 设备信息
   */
  async getDevice() {
    return await this.getDevice();
  }

  /**
   * 更新预警状态
   * @param {String} status 新状态
   * @returns {Promise<Boolean>} 更新结果
   */
  async updateStatus(status) {
    try {
      this.status = status;
      
      if (status === 'resolved') {
        this.resolved_at = new Date();
      }
      
      await this.save();
      return true;
    } catch (error) {
      console.error('更新预警状态失败:', error);
      return false;
    }
  }

  /**
   * 解决预警
   * @param {Number} userId 解决人ID
   * @param {String} notes 解决说明
   * @returns {Promise<Boolean>} 解决结果
   */
  async resolve(userId, notes) {
    try {
      this.status = 'resolved';
      this.resolved_at = new Date();
      this.resolved_by = userId;
      this.resolution_notes = notes;
      
      await this.save();
      return true;
    } catch (error) {
      console.error('解决预警失败:', error);
      return false;
    }
  }
}

// 初始化Alert模型
Alert.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  type: {
    type: DataTypes.STRING(50),
    allowNull: false
  },
  level: {
    type: DataTypes.ENUM('low', 'medium', 'high', 'critical'),
    defaultValue: 'medium'
  },
  message: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  status: {
    type: DataTypes.ENUM('active', 'acknowledged', 'resolved'),
    defaultValue: 'active'
  },
  farm_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'farms',
      key: 'id'
    }
  },
  device_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'devices',
      key: 'id'
    }
  },
  resolved_at: {
    type: DataTypes.DATE,
    allowNull: true
  },
  resolved_by: {
    type: DataTypes.INTEGER,
    allowNull: true
  },
  resolution_notes: {
    type: DataTypes.TEXT,
    allowNull: true
  }
}, {
  sequelize,
  tableName: 'alerts',
  modelName: 'Alert',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

/**
 * 导出预警模型
 * @exports Alert
 */
module.exports = Alert;