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

class Report extends BaseModel {
  static associate(models) {
    // 报表属于用户
    Report.belongsTo(models.User, {
      as: 'creator',
      foreignKey: 'createdBy',
      targetKey: 'id'
    });
  }
}

Report.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(255),
    allowNull: false,
    comment: '报表名称'
  },
  type: {
    type: DataTypes.ENUM('transaction', 'account', 'user'),
    allowNull: false,
    comment: '报表类型'
  },
  format: {
    type: DataTypes.ENUM('excel', 'pdf', 'csv'),
    allowNull: false,
    comment: '报表格式'
  },
  status: {
    type: DataTypes.ENUM('processing', 'completed', 'failed'),
    allowNull: false,
    defaultValue: 'processing',
    comment: '报表状态'
  },
  filePath: {
    type: DataTypes.STRING(500),
    allowNull: true,
    comment: '文件路径'
  },
  parameters: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '生成参数'
  },
  data: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '报表数据'
  },
  error: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '错误信息'
  },
  createdBy: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '创建人ID'
  }
}, {
  sequelize,
  modelName: 'Report',
  tableName: 'reports',
  comment: '报表记录表',
  indexes: [
    {
      fields: ['type', 'status']
    },
    {
      fields: ['createdBy']
    },
    {
      fields: ['createdAt']
    }
  ]
});

module.exports = Report;
