const BaseModel = require('./BaseModel');

class OrderItem extends BaseModel {
  constructor() {
    super('order_items');
  }

  async create(orderItemData) {
    const {
      order_id,
      item_id,
      item_name,
      quantity,
      unit_price,
      tax_amount = 0,
      discount_amount = 0,
      total_price
    } = orderItemData;
    
    const query = `
      INSERT INTO order_items 
      (order_id, item_id, item_name, quantity, unit_price, tax_amount, discount_amount, total_price)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const [result] = await this.db.query(query, [
      order_id, item_id, item_name, quantity, unit_price, tax_amount, discount_amount, total_price
    ]);
    
    return result.insertId;
  }

  async getByOrder(orderId) {
    const [rows] = await this.db.query(
      'SELECT * FROM order_items WHERE order_id = ?',
      [orderId]
    );
    return rows;
  }
 
  async getTopSellingItems(limit = 10, startDate = null, endDate = null) {
    let query = `
      SELECT 
        oi.item_id,
        i.name as item_name,
        SUM(oi.quantity) as total_quantity,
        SUM(oi.total_price) as total_revenue,
        COUNT(DISTINCT oi.order_id) as order_count
      FROM order_items oi
      JOIN items i ON oi.item_id = i.id
      JOIN orders o ON oi.order_id = o.id
      WHERE o.status = 'completed'
    `;
    
    const params = [];
    
    if (startDate) {
      query += ' AND o.created_at >= ?';
      params.push(startDate);
    }
    
    if (endDate) {
      query += ' AND o.created_at <= ?';
      params.push(endDate);
    }
    
    query += `
      GROUP BY oi.item_id, i.name
      ORDER BY total_quantity DESC
      LIMIT ?
    `;
    
    params.push(limit);
    
    const [rows] = await this.db.query(query, params);
    return rows;
  }
}

module.exports = new OrderItem();
