const db = require('../config/database');

class Airline {
  static async getAll() {
    const [rows] = await db.query(
      'SELECT * FROM airlines ORDER BY name ASC'
    );
    return rows;
  }

  static async getActive() {
    const [rows] = await db.query(
      'SELECT * FROM airlines WHERE status = ? ORDER BY name ASC',
      ['active']
    );
    return rows;
  }

  static async getById(id) {
    const [rows] = await db.query(
      'SELECT * FROM airlines WHERE id = ?',
      [id]
    );
    return rows[0];
  }

  static async getByCode(code) {
    const [rows] = await db.query(
      'SELECT * FROM airlines WHERE code = ?',
      [code]
    );
    return rows[0];
  }

  static async create(airlineData) {
    const { name, code, logo_url, status } = airlineData;

    const [result] = await db.query(
      'INSERT INTO airlines (name, code, logo_url, status) VALUES (?, ?, ?, ?)',
      [name, code, logo_url || null, status || 'active']
    );

    return this.getById(result.insertId);
  }

  static async update(id, airlineData) {
    const { name, code, logo_url, status } = airlineData;

    await db.query(
      'UPDATE airlines SET name = ?, code = ?, logo_url = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [name, code, logo_url, status, id]
    );

    return this.getById(id);
  }

  static async delete(id) {
    await db.query('DELETE FROM airlines WHERE id = ?', [id]);
    return { message: 'Havayolu şirketi silindi' };
  }
}

module.exports = Airline;
