const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

/**
 * 设备预警模型
 * 用于管理设备预警信息
 */
const DeviceAlert = sequelize.define('DeviceAlert', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '预警ID'
  },
  device_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '设备ID'
  },
  alert_type: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '预警类型'
  },
  alert_level: {
    type: DataTypes.ENUM('info', 'warning', 'critical'),
    allowNull: false,
    comment: '预警级别：info-信息，warning-警告，critical-严重'
  },
  alert_title: {
    type: DataTypes.STRING(200),
    allowNull: false,
    comment: '预警标题'
  },
  alert_content: {
    type: DataTypes.TEXT,
    comment: '预警内容'
  },
  alert_time: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '预警时间'
  },
  status: {
    type: DataTypes.ENUM('pending', 'processing', 'resolved', 'ignored'),
    defaultValue: 'pending',
    comment: '处理状态：pending-待处理，processing-处理中，resolved-已解决，ignored-已忽略'
  },
  handler_id: {
    type: DataTypes.INTEGER,
    comment: '处理人ID'
  },
  handle_time: {
    type: DataTypes.DATE,
    comment: '处理时间'
  },
  handle_note: {
      type: DataTypes.TEXT,
      comment: '处理备注'
    },
  farm_id: {
    type: DataTypes.INTEGER,
    comment: '所属养殖场ID'
  },
  barn_id: {
      type: DataTypes.INTEGER,
      comment: '所属栏舍ID'
    },
  is_read: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    comment: '是否已读'
  },
  read_time: {
    type: DataTypes.DATE,
    comment: '阅读时间'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    comment: '创建时间'
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    comment: '更新时间'
  }
}, {
  tableName: 'device_alerts',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  comment: '设备预警表',
  indexes: [
    {
      fields: ['device_id']
    },
    {
      fields: ['alert_level']
    },
    {
      fields: ['status']
    },
    {
      fields: ['alert_time']
    },
    {
      fields: ['farm_id']
    }
  ]
});

module.exports = DeviceAlert;