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

/**
 * Find admin account by username (active only)
 * @param {string} username
 * @returns {Promise<Object|null>} admin row or null
 */
async function findByUsername(username) {
  return one(
    'SELECT * FROM admin_accounts WHERE username = :username AND status = 1',
    { username }
  )
}

/**
 * Find admin account by ID (active only)
 * @param {number} adminId
 * @returns {Promise<Object|null>} admin row or null
 */
async function findById(adminId) {
  return one(
    'SELECT * FROM admin_accounts WHERE admin_id = :admin_id AND status = 1',
    { admin_id: adminId }
  )
}

/**
 * Update admin password hash and clear legacy salt
 * @param {number} adminId
 * @param {string} passwordHash - bcrypt hash
 * @returns {Promise<Array>} query result
 */
async function updatePassword(adminId, passwordHash) {
  return query(
    'UPDATE admin_accounts SET password_hash = :password_hash, password_salt = :password_salt WHERE admin_id = :admin_id',
    { password_hash: passwordHash, password_salt: '', admin_id: adminId }
  )
}

/**
 * Auto-migrate password from legacy SHA-256 to bcrypt
 * @param {number} adminId
 * @param {string} newHash - bcrypt hash
 * @returns {Promise<Array>} query result
 */
async function migratePassword(adminId, newHash) {
  return updatePassword(adminId, newHash)
}

/**
 * Get dashboard aggregate counts (devices, users, treatments, active subscriptions)
 * @returns {Promise<{device_count: number, user_count: number, treatment_count: number, subscription_count: number}>}
 */
async function getDashboardCounts() {
  const rows = await Promise.all([
    query('SELECT COUNT(*) AS total FROM devices', {}),
    query('SELECT COUNT(*) AS total FROM users', {}),
    query('SELECT COUNT(*) AS total FROM treatment_records', {}),
    query('SELECT COUNT(*) AS total FROM subscriptions WHERE status = 1 AND expire_time > NOW()', {})
  ])
  return {
    device_count: rows[0][0].total,
    user_count: rows[1][0].total,
    treatment_count: rows[2][0].total,
    subscription_count: rows[3][0].total
  }
}

/**
 * Get subscription breakdown stats (monthly/yearly/trial counts, monthly revenue)
 * @returns {Promise<Object>} { monthly_count, yearly_count, trial_count, monthly_revenue }
 */
async function getSubscriptionStats() {
  const rows = await query(
    'SELECT ' +
    "SUM(CASE WHEN plan = 'monthly' AND status = 1 AND expire_time > NOW() THEN 1 ELSE 0 END) AS monthly_count, " +
    "SUM(CASE WHEN plan = 'yearly' AND status = 1 AND expire_time > NOW() THEN 1 ELSE 0 END) AS yearly_count, " +
    "SUM(CASE WHEN plan = 'trial' AND status = 1 AND expire_time > NOW() THEN 1 ELSE 0 END) AS trial_count, " +
    'COALESCE(SUM(CASE WHEN MONTH(start_time) = MONTH(NOW()) AND YEAR(start_time) = YEAR(NOW()) THEN amount ELSE 0 END), 0) AS monthly_revenue ' +
    'FROM subscriptions',
    {}
  )
  return rows[0] || {}
}

module.exports = {
  findByUsername,
  findById,
  updatePassword,
  migratePassword,
  getDashboardCounts,
  getSubscriptionStats
}
