const { getConnection } = require('../config/database');

class Platform {
  static async findAll() {
    const connection = getConnection();
    const [rows] = await connection.execute(
      'SELECT * FROM platforms WHERE is_active = TRUE ORDER BY sort_order ASC'
    );
    return rows;
  }

  static async findById(id) {
    const connection = getConnection();
    const [rows] = await connection.execute(
      'SELECT * FROM platforms WHERE id = ?',
      [id]
    );
    return rows[0];
  }

  static async findBySlug(slug) {
    const connection = getConnection();
    const [rows] = await connection.execute(
      'SELECT * FROM platforms WHERE slug = ? AND is_active = TRUE',
      [slug]
    );
    return rows[0];
  }

  static async create(platformData) {
    const connection = getConnection();
    const { name, slug, icon, color, sort_order } = platformData;
    
    const [result] = await connection.execute(
      'INSERT INTO platforms (name, slug, icon, color, sort_order) VALUES (?, ?, ?, ?, ?)',
      [name, slug, icon, color, sort_order || 0]
    );
    
    return { id: result.insertId, ...platformData };
  }

  static async update(id, platformData) {
    const connection = getConnection();
    const { name, slug, icon, color, sort_order, is_active } = platformData;
    
    await connection.execute(
      'UPDATE platforms SET name = ?, slug = ?, icon = ?, color = ?, sort_order = ?, is_active = ? WHERE id = ?',
      [name, slug, icon, color, sort_order, is_active, id]
    );
    
    return await this.findById(id);
  }

  static async delete(id) {
    const connection = getConnection();
    await connection.execute('DELETE FROM platforms WHERE id = ?', [id]);
  }
}

module.exports = Platform;