// models/consumableCategoryModel.js
const { getDb } = require('../dbPool');

const ConsumableCategoryModel = {
  async getAll(activeOnly = true) {
    const db = await getDb();
    let sql = 'SELECT * FROM consumable_categories';
    if (activeOnly) sql += ' WHERE is_active = 1';
    sql += ' ORDER BY sort_order, category_name';
    const [rows] = await db.query(sql);
    return rows;
  },

  async getById(id) {
    const db = await getDb();
    const [rows] = await db.query('SELECT * FROM consumable_categories WHERE category_id = ?', [id]);
    return rows[0] || null;
  },

  async create({ categoryCode, categoryName, icon, colorBg, colorFg, sortOrder }) {
    const db = await getDb();
    const [result] = await db.query(
      `INSERT INTO consumable_categories (category_code, category_name, icon, color_bg, color_fg, sort_order)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [categoryCode, categoryName, icon || 'fa-box', colorBg || '#dbeafe', colorFg || '#1e40af', sortOrder || 0]
    );
    return this.getById(result.insertId);
  },

  async update(id, { categoryName, icon, colorBg, colorFg, sortOrder }) {
    const db = await getDb();
    await db.query(
      `UPDATE consumable_categories SET category_name = ?, icon = ?, color_bg = ?, color_fg = ?, sort_order = ?
       WHERE category_id = ?`,
      [categoryName, icon, colorBg, colorFg, sortOrder, id]
    );
    return this.getById(id);
  },

  async deactivate(id) {
    const db = await getDb();
    await db.query('UPDATE consumable_categories SET is_active = 0 WHERE category_id = ?', [id]);
    return this.getById(id);
  }
};

module.exports = ConsumableCategoryModel;
