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

/**
 * 订单模型
 * @typedef {Object} Order
 * @property {number} id - 订单唯一标识
 * @property {number} user_id - 用户ID
 * @property {number} total_amount - 订单总金额（单位：分）
 * @property {string} status - 订单状态
 * @property {string} payment_status - 支付状态
 * @property {string} shipping_address - 收货地址
 * @property {Date} created_at - 创建时间
 * @property {Date} updated_at - 更新时间
 */
class Order extends BaseModel {
  /**
   * 获取用户的所有订单
   * @param {Number} userId 用户ID
   * @param {Object} options 查询选项
   * @returns {Promise<Array>} 订单列表
   */
  static async getUserOrders(userId, options = {}) {
    return await this.findAll({
      where: { user_id: userId },
      ...options
    });
  }

  /**
   * 获取订单详情，包括订单项
   * @returns {Promise<Object>} 订单详情
   */
  async getOrderDetails() {
    return await Order.findByPk(this.id, {
      include: [{ model: sequelize.models.OrderItem }]
    });
  }

  /**
   * 计算订单总金额
   * @returns {Promise<Number>} 订单总金额
   */
  async calculateTotal() {
    const orderItems = await this.getOrderItems();
    let total = 0;
    
    for (const item of orderItems) {
      total += item.price * item.quantity;
    }
    
    this.total_amount = total;
    await this.save();
    
    return total;
  }

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

  /**
   * 更新支付状态
   * @param {String} paymentStatus 新支付状态
   * @returns {Promise<Boolean>} 更新结果
   */
  async updatePaymentStatus(paymentStatus) {
    try {
      this.payment_status = paymentStatus;
      await this.save();
      return true;
    } catch (error) {
      console.error('更新支付状态失败:', error);
      return false;
    }
  }
}

// 初始化Order模型
Order.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  total_amount: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '单位：分'
  },
  status: {
    type: DataTypes.ENUM('pending', 'processing', 'shipped', 'delivered', 'cancelled'),
    allowNull: false,
    defaultValue: 'pending'
  },

}, {
  sequelize,
  tableName: 'orders',
  modelName: 'Order',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

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