/**
 * ORM配置文件
 * @file orm-config.js
 * @description 提供统一的ORM配置和扩展功能
 */
const { Sequelize, DataTypes, Op } = require('sequelize');
const sequelize = require('./database-pool').sequelize;
const queryOptimizer = require('./query-optimizer');

/**
 * 默认模型选项
 */
const defaultModelOptions = {
  timestamps: true,       // 默认添加 createdAt 和 updatedAt
  paranoid: true,         // 软删除（添加 deletedAt 而不是真正删除数据）
  underscored: true,      // 使用下划线命名法 (例如: created_at 而不是 createdAt)
  freezeTableName: false, // 使用模型名称的复数形式作为表名
  charset: 'utf8mb4',     // 字符集
  collate: 'utf8mb4_unicode_ci', // 排序规则
};

/**
 * 创建模型时的默认字段
 */
const defaultFields = {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '主键ID'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
    comment: '创建时间'
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
    onUpdate: Sequelize.literal('CURRENT_TIMESTAMP'),
    comment: '更新时间'
  },

};

/**
 * 扩展Sequelize模型功能
 * @param {Object} modelClass Sequelize模型类
 */
function extendModel(modelClass) {
  // 添加通用的查询方法
  modelClass.findAllActive = function(options = {}) {
    return this.findAll({
      ...options
    });
  };

  // 添加分页查询方法
  modelClass.findAllPaginated = function({ page = 1, pageSize = 10, ...options } = {}) {
    const offset = (page - 1) * pageSize;
    return this.findAndCountAll({
      ...options,
      limit: pageSize,
      offset
    }).then(result => ({
      rows: result.rows,
      total: result.count,
      page,
      pageSize,
      totalPages: Math.ceil(result.count / pageSize)
    }));
  };

  // 添加批量更新方法
  modelClass.bulkUpdateById = async function(records, options = {}) {
    if (!Array.isArray(records) || records.length === 0) {
      return [];
    }

    const results = [];
    for (const record of records) {
      if (!record.id) continue;
      const [affectedCount, affectedRows] = await this.update(record, {
        where: { id: record.id },
        returning: true,
        ...options
      });
      if (affectedCount > 0 && affectedRows.length > 0) {
        results.push(affectedRows[0]);
      }
    }
    return results;
  };
}

/**
 * 初始化ORM
 * @returns {Object} Sequelize实例和工具函数
 */
function initORM() {
  // 扩展Sequelize.Model
  extendModel(Sequelize.Model);

  return {
    sequelize,
    Sequelize,
    DataTypes,
    Op,
    defaultModelOptions,
    defaultFields,
    queryOptimizer
  };
}

module.exports = initORM();