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

/**
 * 订单项模型
 * @typedef {Object} OrderItem
 * @property {number} id - 订单项唯一标识
 * @property {number} order_id - 订单ID
 * @property {number} product_id - 产品ID
 * @property {number} quantity - 数量
 * @property {number} price - 单价（单位：分）
 * @property {Date} created_at - 创建时间
 */
class OrderItem extends BaseModel {
  /**
   * 获取订单的所有订单项
   * @param {Number} orderId 订单ID
   * @returns {Promise<Array>} 订单项列表
   */
  static async getOrderItems(orderId) {
    return await this.findAll({
      where: { order_id: orderId },
      include: [{ model: sequelize.models.Product }]
    });
  }

  /**
   * 计算订单项总金额
   * @returns {Number} 总金额
   */
  getTotalPrice() {
    return this.price * this.quantity;
  }

  /**
   * 更新订单项数量
   * @param {Number} quantity 新数量
   * @returns {Promise<Boolean>} 更新结果
   */
  async updateQuantity(quantity) {
    try {
      if (quantity <= 0) {
        throw new Error('数量必须大于0');
      }
      
      // 检查产品库存
      const product = await sequelize.models.Product.findByPk(this.product_id);
      
      if (!product) {
        throw new Error('产品不存在');
      }
      
      const quantityDiff = quantity - this.quantity;
      
      if (quantityDiff > 0 && !product.hasEnoughStock(quantityDiff)) {
        throw new Error('产品库存不足');
      }
      
      // 使用事务确保数据一致性
      const result = await sequelize.transaction(async (t) => {
        // 更新订单项数量
        this.quantity = quantity;
        await this.save({ transaction: t });
        
        // 更新产品库存
        await product.updateStock(-quantityDiff, { transaction: t });
        
        // 更新订单总金额
        const order = await sequelize.models.Order.findByPk(this.order_id, { transaction: t });
        await order.calculateTotal({ transaction: t });
        
        return true;
      });
      
      return result;
    } catch (error) {
      console.error('更新订单项数量失败:', error);
      return false;
    }
  }
}

// 初始化OrderItem模型
OrderItem.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  order_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'orders',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  product_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'products',
      key: 'id'
    },
    onDelete: 'RESTRICT'
  },
  quantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 1,
    validate: {
      min: 1
    }
  },
  price: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '单位：分'
  }
}, {
  sequelize,
  tableName: 'order_items',
  modelName: 'OrderItem',
  timestamps: false
});

/**
 * 导出订单项模型
 * @exports OrderItem
 */
module.exports = OrderItem;