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

exports.getAll = async (_req, res, next) => {
  try {
    const [rows] = await db.query('SELECT * FROM airlines ORDER BY code');
    res.json(rows);
  } catch (err) {
    next(err);
  }
};

exports.getById = async (req, res, next) => {
  try {
    const [rows] = await db.query('SELECT * FROM airlines WHERE id = ?', [req.params.id]);
    if (rows.length === 0) return res.status(404).json({ error: 'Airline not found' });
    res.json(rows[0]);
  } catch (err) {
    next(err);
  }
};

exports.create = async (req, res, next) => {
  try {
    const { name, code } = req.body;
    if (!name || !code) return res.status(400).json({ error: 'name and code are required' });
    const [result] = await db.query(
      'INSERT INTO airlines (name, code) VALUES (?, ?)',
      [name, code.toUpperCase()]
    );
    const [rows] = await db.query('SELECT * FROM airlines WHERE id = ?', [result.insertId]);
    res.status(201).json(rows[0]);
  } catch (err) {
    next(err);
  }
};

exports.update = async (req, res, next) => {
  try {
    const { name, code } = req.body;
    const [result] = await db.query(
      `UPDATE airlines SET
         name = COALESCE(?, name),
         code = COALESCE(?, code)
       WHERE id = ?`,
      [name, code ? code.toUpperCase() : null, req.params.id]
    );
    if (result.affectedRows === 0) return res.status(404).json({ error: 'Airline not found' });
    const [rows] = await db.query('SELECT * FROM airlines WHERE id = ?', [req.params.id]);
    res.json(rows[0]);
  } catch (err) {
    next(err);
  }
};

exports.remove = async (req, res, next) => {
  try {
    const [result] = await db.query('DELETE FROM airlines WHERE id = ?', [req.params.id]);
    if (result.affectedRows === 0) return res.status(404).json({ error: 'Airline not found' });
    res.json({ message: 'Airline deleted' });
  } catch (err) {
    next(err);
  }
};
