Ruby_Then

def where(codes:, only_selling: false, nutritional_type: nil)
  Records::Item.joins(:sales_setting)
               .where(code: codes)
               .then { |items| filter_by_nutritional_type(items, nutritional_type) }
               .then { |items| only_selling ? filter_by_available_only(items) : items }
               .map(&:code)
end

private

# 栄養タイプでフィルタリングする
# @param [ActiveRecord::Relation<Records::Item>] item_records 商品レコード
# @param [String, nil] nutritional_type 栄養タイプ
# @return [ActiveRecord::Relation<Records::Item>] 栄養タイプでフィルタリングした商品レコード
def filter_by_nutritional_type(item_records, nutritional_type)
  nutritional_type.present? ? item_records.where(nutritional_type: nutritional_type) : item_records
end

# 販売可能な商品のみにフィルタリングする
# @param [ActiveRecord::Relation<Records::Item>] item_records 商品レコード
# @return [ActiveRecord::Relation<Records::Item>] 販売可能な商品のみをフィルタリングした商品レコード
def filter_by_available_only(item_records)
  today = Time.zone.today
  item_records.where(sales_setting: { selling_from_date: ..today, selling_to_date: today.. })
              .or(item_records.where(sales_setting: { selling_from_date: ..today, selling_to_date: nil }))
end