/**
 * Builds SQL clause and params to filter by country_id, location_id (site), department_id (work area).
 * Used for sat_audits and any query joining sat_audits (alias "a").
 * @param {object} filter - { country_id, location_id, department_id } (optional; from req.query)
 * @returns {{ clause: string, params: any[] }}
 */
function buildAuditFilter(filter) {
  if (!filter || (filter.country_id == null && filter.location_id == null && filter.department_id == null)) {
    return { clause: '', params: [] };
  }
  const conditions = [];
  const params = [];
  if (filter.country_id != null && filter.country_id !== '') {
    conditions.push('a.country_id = ?');
    params.push(Number(filter.country_id));
  }
  if (filter.location_id != null && filter.location_id !== '') {
    conditions.push('a.location = ?');
    params.push(Number(filter.location_id));
  }
  if (filter.department_id != null && filter.department_id !== '') {
    conditions.push('a.department_id = ?');
    params.push(Number(filter.department_id));
  }
  if (conditions.length === 0) return { clause: '', params: [] };
  return { clause: ' AND ' + conditions.join(' AND '), params };
}

/**
 * Parse location filter from request query.
 * @param {object} req - Express request (req.query)
 * @returns {{ country_id?: string, location_id?: string, department_id?: string }}
 */
function getLocationFilterFromRequest(req) {
  const q = req && req.query;
  if (!q) return {};
  return {
    country_id: q.country_id,
    location_id: q.location_id,
    department_id: q.department_id,
  };
}

module.exports = {
  buildAuditFilter,
  getLocationFilterFromRequest,
};
