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

class CategoryOrder extends BaseModel {
  constructor() {
    super('category_order');
  }

  async create(orderData) {
    const { category_id, display_order } = orderData;
    const query = `
      INSERT INTO category_order 
      (category_id, display_order)
      VALUES (?, ?)
    `;
    const [result] = await this.db.query(query, [category_id, display_order]);
    return result.insertId;
  }

  async update(id, orderData) {
    const { category_id, display_order } = orderData;
    const query = `
      UPDATE category_order SET
        category_id = ?,
        display_order = ?,
        updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;
    const [result] = await this.db.query(query, [category_id, display_order, id]);
    return result.affectedRows > 0;
  }

  async findByCategory(categoryId) {
    const [rows] = await this.db.query('SELECT * FROM category_order WHERE category_id = ?', [categoryId]);
    return rows[0];
  }

  async updateDisplayOrders(orders) {
    const query = 'UPDATE category_order SET display_order = ? WHERE id = ?';
    const values = orders.map(order => [order.display_order, order.id]);
    
    const connection = await this.db.getConnection();
    try {
      await connection.beginTransaction();
      
      for (const [displayOrder, id] of values) {
        await connection.query(query, [displayOrder, id]);
      }
      
      await connection.commit();
      return true;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }
}

module.exports = new CategoryOrder();
