const { query, one } = require('../lib/db')

/**
 * List all firmware files ordered by creation date (newest first)
 * @returns {Promise<Array>}
 */
async function list() {
  return query(
    'SELECT firmware_id, version, device_type, cos_key, size_bytes, sha256, status, created_at FROM firmware_files ORDER BY created_at DESC',
    {}
  )
}

/**
 * Create a firmware record
 * @param {Object} firmware
 * @param {string} firmware.version
 * @param {string} [firmware.device_type]
 * @param {string} firmware.cos_key
 * @param {number} [firmware.size_bytes]
 * @param {string} [firmware.sha256]
 * @param {number} [firmware.status] - 0=disabled, 1=enabled (default 1)
 * @returns {Promise<Object>} query result with insertId
 */
async function create(firmware) {
  return query(
    'INSERT INTO firmware_files (version, device_type, cos_key, size_bytes, sha256, status) VALUES (:version, :device_type, :cos_key, :size_bytes, :sha256, :status)',
    {
      version: firmware.version,
      device_type: firmware.device_type || '',
      cos_key: firmware.cos_key,
      size_bytes: Number(firmware.size_bytes || 0),
      sha256: firmware.sha256 || '',
      status: firmware.status === 0 ? 0 : 1
    }
  )
}

/**
 * Update firmware status (enable/disable)
 * @param {number} firmwareId
 * @param {number} status - 0 or 1
 * @returns {Promise<Array>} query result
 */
async function updateStatus(firmwareId, status) {
  return query(
    'UPDATE firmware_files SET status = :status WHERE firmware_id = :firmware_id',
    { status, firmware_id: firmwareId }
  )
}

/**
 * Find the latest enabled firmware
 * @returns {Promise<Object|null>}
 */
async function findLatest() {
  return one(
    'SELECT * FROM firmware_files WHERE status = 1 ORDER BY created_at DESC LIMIT 1',
    {}
  )
}

module.exports = {
  list,
  create,
  updateStatus,
  findLatest
}
