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

class OrderStatusHistory extends BaseModel {
  constructor() {
    super('order_status_history');
  }

  async create(historyData) {
    const { order_id, status, notes = null } = historyData;
    
    const query = `
      INSERT INTO order_status_history 
      (order_id, status, notes)
      VALUES (?, ?, ?)
    `;
    
    const [result] = await this.db.query(query, [order_id, status, notes]);
    return result.insertId;
  }

  async getByOrder(orderId) {
    const [rows] = await this.db.query(
      'SELECT * FROM order_status_history WHERE order_id = ? ORDER BY created_at DESC',
      [orderId]
    );
    return rows;
  }

  async getLatestStatus(orderId) {
    const [rows] = await this.db.query(
      'SELECT * FROM order_status_history WHERE order_id = ? ORDER BY created_at DESC LIMIT 1',
      [orderId]
    );
    return rows[0] || null;
  }

  async getOrdersByStatus(status, startDate = null, endDate = null) {
    let query = `
      SELECT osh.*, o.order_number, o.total_amount, o.customer_name
      FROM order_status_history osh
      JOIN orders o ON osh.order_id = o.id
      WHERE osh.status = ?
    `;
    
    const params = [status];
    
    if (startDate) {
      query += ' AND DATE(osh.created_at) >= ?';
      params.push(startDate);
    }
    
    if (endDate) {
      query += ' AND DATE(osh.created_at) <= ?';
      params.push(endDate);
    }
    
    query += ' ORDER BY osh.created_at DESC';
    
    const [rows] = await this.db.query(query, params);
    return rows;
  }
}

module.exports = new OrderStatusHistory();
